-1

When I try this code:

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

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

I get this result:

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

I.e., the list is not changed. Why is that? How can I change all those strs to ints in the nested list?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
pearbear
  • 1,025
  • 4
  • 18
  • 23
  • 2
    `int(item)` <-- a value is computed and then *discarded*. Put it somewhere. –  Oct 02 '12 at 02:50

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
  • 84,695
  • 9
  • 117
  • 138