45

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]

3
  • for item in array item*=1
    – AbiusX
    Commented Mar 15, 2011 at 0:09
  • Why do you call 'array' what are lists ? See: (docs.python.org/library/array.html#module-array)
    – eyquem
    Commented Mar 15, 2011 at 1:33
  • 1
    MATHY people call Python lists an array. A 2-d list/array is a matrix. I believe the origin is from linear algebra.
    – James VB
    Commented Feb 20, 2022 at 22:23

3 Answers 3

84

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]
2
  • 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]: Commented Dec 30, 2017 at 0:19
  • The OP said numbers... so a better answer would be [float(x) for x in current_array] which also handles non-integer values Commented Dec 27, 2021 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']))
2
  • 2
    A perfect example why declarative style might be much better than imperative IMHO.
    – Piohen
    Commented Jul 9, 2014 at 9:25
  • It however does not return a list, but a map. At least after I did x = map(int, ['1','-1','1']) I could not call len(x). Commented May 11, 2021 at 9:49
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

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.