0

In the belove program

list = [1, 2, 3, 4, 5, 6, 7]
for i in list:
    list.pop()
    print(list)
print(list)

I am getting output as

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

and why not

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 2, 3]
[1, 2]
[1]
  • You should iterate the list at the same time as you're modifying it. See https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it – Alexander Mar 02 '23 at 19:38
  • `for i in list:` is going to produce the element at index 0 in the list, then the element at index 1, then the element at index 2, then the element at index 3. At that point the loop terminates, because there are no elements beyond that index. – jasonharper Mar 02 '23 at 19:38

0 Answers0