36

Possible Duplicate:
What is the easiest way to convert list with str into list with int?

current array: ['1','-1','1'] desired array: [1,-1,1]

Community
  • 1
  • 1
NullVoxPopuli
  • 56,640
  • 72
  • 202
  • 343

3 Answers3

68

Use int which converts a string to an int, inside a list comprehension, like this:

desired_array = [int(numeric_string) for numeric_string in current_array]
sepp2k
  • 353,842
  • 52
  • 662
  • 667
  • Worth noting that you can use this method for casting to a class as well, e.g. `for instance in [MyClass(name) for name in list_of_names]:` – brandonscript Dec 30 '17 at 00:19
  • The OP said numbers... so a better answer would be `[float(x) for x in current_array]` which also handles non-integer values – John Henckel Dec 27 '21 at 15:52
53

List comprehensions are the way to go (see @sepp2k's answer). Possible alternative with map:

list(map(int, ['1','-1','1']))
miku
  • 172,072
  • 46
  • 300
  • 307
0

Let's see if I remember python

list = ['1' , '2', '3']
list2 = []
for i in range(len(list)):
    t = int(list[i])
    list2.append(t)

print list2

edit: looks like the other responses work out better

Duniyadnd
  • 3,902
  • 1
  • 21
  • 25