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]
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]
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]
for instance in [MyClass(name) for name in list_of_names]:
Commented
Dec 30, 2017 at 0:19
[float(x) for x in current_array]
which also handles non-integer values
Commented
Dec 27, 2021 at 15:52
List comprehensions are the way to go (see @sepp2k's answer). Possible alternative with map
:
list(map(int, ['1','-1','1']))
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