-1

Possible Duplicate:
How to convert strings into integers in python?

listy = [['1', '2', '3', '4', '5'], "abc"]

for item in listy[0]:
    int(item)

print listy

In a nested list, how can I change all those strings to ints? What's above gives me an output of:

[['1', '2', '3', '4', '5'], 'abc']

Why is that?

Thanks in advance!

Community
  • 1
  • 1
pearbear
  • 943
  • 4
  • 16
  • 22

1 Answers1

0

You need to assign the converted items back to the sub-list (listy[0]):

listy[0][:] = [int(x) for x in listy[0]]

Explanation:

for item in listy[0]:
    int(item)

The above iterates over the items in the sub-list and converts them to integers, but it does not assign the result of the expression int(item) to anything. Therefore the result is lost.

[int(x) for x in listy[0]] is a list comprehension (kind of shorthand for your for loop) that iterates over the list, converting each item to an integer and returning a new list. The new list is then assigned back (in place, optional) to the outer list.

This is a very custom solution for your specific question. A more general solution involves recursion to get at the sub-lists, and some way of detecting the candidates for numeric conversion.

mhawke
  • 80,261
  • 9
  • 108
  • 134