1

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?

wim
  • 338,267
  • 99
  • 616
  • 750
zzdever
  • 37
  • 4
  • I'm thinking that it uses an internal indexer, so when you start you're at index 0, then it jumps to 1 and so on, but since you're also deleting stuff from the array, l[1] was originally 20 but is now 30 so the end result is what you're getting. Just a speculation since I'm not a pro at python – A. L Mar 14 '17 at 02:31
  • This might help: http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating – Craig Mar 14 '17 at 02:31
  • And another: http://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list – Craig Mar 14 '17 at 02:32
  • 1
    Did you do any research at all? Google anything? – TigerhawkT3 Mar 14 '17 at 02:56

2 Answers2

2

'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.

Wright
  • 3,370
  • 10
  • 27
  • Note that though it's true that CPython behaves like this, that behavior is afaik unspecified and should not be depended upon. – spectras Mar 14 '17 at 02:40
  • In the future, please flag duplicate questions for closure as such rather than answering them, as the latter increases fragmentation and makes the site harder to navigate. – TigerhawkT3 Mar 14 '17 at 02:58
2

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
[]
Icyblade
  • 223
  • 1
  • 5
  • 11
  • In the future, please flag duplicate questions for closure as such rather than answering them, as the latter increases fragmentation and makes the site harder to navigate. – TigerhawkT3 Mar 14 '17 at 02:58
  • 1
    @TigerhawkT3 got it, thanks for the information :-) – Icyblade Mar 14 '17 at 03:01