0

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!

Tim
  • 1
  • 141
  • 372
  • 590

2 Answers2

3

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.

metatoaster
  • 17,419
  • 5
  • 55
  • 66
1
i = iter(list)
while i.next != None:
    print int(i.next())
Yogesh D
  • 1,663
  • 2
  • 23
  • 38