Python: How do I convert an array of strings to an array of numbers?

Question:

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]

Asked By: NullVoxPopuli

||

Answers:

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]
Answered By: sepp2k

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

list(map(int, ['1','-1','1']))
Answered By: miku

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

Answered By: Duniyadnd
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.