Tim
Tim

Reputation: 99428

convert a list of strings to a list of numbers?

I would like to convert a list of following strings into integers:

>>> tokens
['2', '6']
>>> int(tokens)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'list'

Other than writing a for loop to convert each member of the list tokens, is there a better way to do that? Thanks!

Upvotes: 0

Views: 120

Answers (2)

Yogesh D
Yogesh D

Reputation: 1681

i = iter(list)
while i.next != None:
    print int(i.next())

Upvotes: 1

metatoaster
metatoaster

Reputation: 18908

Just use list comprehension:

[int(t) for t in tokens]

Alternatively map the int over the list

map(int, tokens)

However map is changed in python3, so it creates an instance of the map and you would have to cast that back into a list if you want the list.

Upvotes: 3

Related Questions