In this Python snippet:
l = [10,20,30,40,50]
for i in l:
l.remove(i)
print(i)
print(l)
The output is:
10
30
50
[20, 40]
This behavior in Python takes me several hours to debug. How does "for...in..." actually work?
In this Python snippet:
l = [10,20,30,40,50]
for i in l:
l.remove(i)
print(i)
print(l)
The output is:
10
30
50
[20, 40]
This behavior in Python takes me several hours to debug. How does "for...in..." actually work?
'i' in your code takes the value of each of the elements in your l list. So typing for i in l
i will first become the first index, in this case 10, then perform the code underneath, which removes i from the list so now your list is [20,30,40,50]
it prints i.. Which was 10. it then hops onto the next index, l[1] which is NOW 30 and performs the code.
As @A. Lau has mentioned, in the second iteration of your for
loop, i
will be indexed as the second element of l
, thus l[1]=30
will be assigned to i
.
If you really want to delete element in a for loop, you can try something like this:
l = [10,20,30,40,50]
for i in l[:]:
l.remove(i)
print(i)
print(l)
The result will be:
10
20
30
40
50
[]