43

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
  • 61,906
  • 73
  • 206
  • 352

3 Answers3

82

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
  • 363,768
  • 54
  • 674
  • 675
  • 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
58

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

list(map(int, ['1','-1','1']))
miku
  • 181,842
  • 47
  • 306
  • 310
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
  • 4,013
  • 1
  • 22
  • 29