-3

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];
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • What have you tried and where are you stuck? Please post your attempt and any error messages, including the complete traceback. – kindall Jan 05 '23 at 19:40
  • You can do it using ``list(map(int, numbers))`` – YousefZ01 Jan 05 '23 at 19:41
  • Welcome to SO. This isn't a discussion forum or tutorial. Please take the [tour] and take the time to read [ask], [mre] and the other links found on those pages. – wwii Jan 05 '23 at 19:43

5 Answers5

1

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))
jsbueno
  • 99,910
  • 10
  • 151
  • 209
1

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.

Chandler Bong
  • 461
  • 1
  • 3
  • 18
0

you can use generator objects

[int(i) for i in numbers]

or mapping...

list(map(int,['1','2','3']))
0

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]
aedt
  • 1
  • 1
  • 1
    That else block isn’t needed, and won’t be executed. If converting to an int fails an exception will be thrown, so it’s not possible the type isn’t int once the if statement is reached. – BTables Jan 05 '23 at 20:04
-1

You can use the below example:-

numbers = ['3', '5', '7', '9']
numbers = list(map(int, numbers))
print(numbers)
BTables
  • 4,413
  • 2
  • 11
  • 30