Converting Strings to int in List

Question:

have a list with numeric strings, like so:

numbers = ['1', '5', '10', '8'];

I would like to convert every list element to integer, so it would look like this:

numbers = [1, 5, 10, 8];
Asked By: Aarush Kaura

||

Answers:

The natural Python way of doing this is using list comprehensions:

intlist = [int(element) for element in stringlist]

This syntax is peculiar to the Python language and is a way to perform a "map" with an optional filtering step for all elements of a sequnce.

An alterantive way, which will be more familiar for programmers that know other languages is to use the map built-in: in it, a function is passed as the first parameter, and the sequence to be processed as the second parameter. The object returned by map is an iterator, that will only perform the calculations on each item as it is requested. If you want an output list, you should build a list out of the object returned by map:

numbers = list(map(int, stringlist))
Answered By: jsbueno

you can use generator objects

[int(i) for i in numbers]
Answered By: Frost Dream

You can use a simple function called map:

numbers = ['1', '5', '10', '8']
numbers = list(map(int, numbers))
print(numbers)

This will map the function int to each element in the iterable. Note that the first argument the map is a function.

Answered By: Chandler Bong

You can use the below example:-

numbers = ['3', '5', '7', '9']
numbers = list(map(int, numbers))
print(numbers)
Answered By: khushi singh

Sometimes int() gives convertion error if the input it’s not a valid variable. In that case must create a code that wraps all convertion error.

numbers = []
not_converted = []
for element in string_numbers:
   try:
      number = int(element)
      if isinstance(number, int):
         numbers.append(number)
      else:
         not_converted.append(element)
   except:
      not_converted.append(element)

If you expect that the input it’s aways a string int you can simply convert like:

numbers = [int(element) for element in string_numbers]
Answered By: aedt
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.