Reputation: 1281
I have the following test code in Python:
lst1 = ["1", "2", "3"]
lst2 = ["4", "5", "6"]
lst3 = ["7", "8", "9"]
numbers = [lst1, lst2, lst3]
for lst in numbers:
lst = list(map(int, lst))
print (numbers)
What I'm trying to do is convert all the string variables in lst1
, lst2
and lst3
, which are all sublists inside the list numbers
, into integers. I'm using the map()
function to achieve this by iterating through each list and converting the list, but somehow, it's not working.
Now, I tried a different method using the following code:
numbers = [list(map(int, lst)) for lst in numbers]
For some reason, this works. Does anyone know why the former code doesn't work and the latter does? I'd just like to wrap my head around it so that I fully understand why it doesn't work.
Thanks!
Upvotes: 0
Views: 1209
Reputation: 33
In the code you wrote the value is being updated in the lst variable an not in the numbers list. But the other code works because you have create a new array with the desired values and assigned it to numbers array itself. You could also do this -
numbers = map(lambda x: map(int, x), numbers)
Upvotes: 1
Reputation: 2880
List Comprehension would be faster in this case
integer_list = [int(i) for j in numbers for i in j]
print(integer_list) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
timeit output:
100000 loops, best of 3: 3.5 µs per loop
You can also use generators
list_generator = (int(i) for j in numbers for i in j)
print(list(list_generator) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Timeit result:
The slowest run took 5.31 times longer than the fastest.
This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 359 ns per loop
Upvotes: 0
Reputation: 18906
This is about updating your numbers variable inside the loop (which simply does not work). I normally work around that doing this:
lst1 = ["1", "2", "3"]
lst2 = ["4", "5", "6"]
lst3 = ["7", "8", "9"]
numbers = [lst1, lst2, lst3]
for ind,lst in enumerate(numbers):
numbers[ind] = list(map(int, lst))
print (numbers)
Also found this questions which appears to respond a similar problem. How to modify list entries during for loop?
Upvotes: 0
Reputation: 15071
for lst in numbers:
lst = list(map(int, lst))
creates a reference lst
that iterates through numbers
, then at each iteration you reassign that reference to a new list, this doesn't change the content of the original list.
This is the same behavior as
x = 4
y = x
y = 2
which doesn't change the value of x
Upvotes: 4
Reputation: 11453
You are printing numbers
which is original list of list instead of lst
which is modified new list.
Try:
for lst in numbers:
lst = list(map(int, lst))
print (lst)
>>>
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
>>>
Upvotes: 0