0
lst = [1,2,3,4,5]
def rem_items(lst):
    for i in lst:
        print(lst)
        time.sleep(1)
        lst.remove(i)


rem_items(lst)

returns

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

I can understand the first two lines, but why does it remove 3 instead of 2?
And why is it stopping after removing 3, not 2,4,5?

Thanks in advance

juanpa.arrivillaga
  • 77,035
  • 9
  • 115
  • 152
Jinmo Chong
  • 81
  • 11

2 Answers2

1

You are modifying the list while iterating over it. This is generally a Bad Thing to do and can lead to unpredictable results.

See here for more info: Modifying list while iterating

Buddy
  • 10,627
  • 5
  • 40
  • 57
1

You are iterating over the list [1,2,3,4,5] and modifying its length.
Writing

for i in lst:
    print(lst)
    time.sleep(1)
    lst.remove(i)

is the same as writing

lst_iter = iter(lst):
for i in lst_iter:
    print(lst)
    time.sleep(1)
    lst.remove(i)

Internally iterator holds a pointer aka index aka position of current item in the list. The loop directive calls i=next(lst_iter) internally, until StopIteration exception is raised.

In your case calling next(lst_iter) for the 1st time returns first element of list [1,2,3,4,5], which is 1. Calling next(lst_iter) for the 2nd time returns second element of list [2,3,4,5], which is 3.

Andrey
  • 723
  • 5
  • 22