0

I have started learning Python. So I tried to run the following program:

nom = [1, 2, 3, 4, 5, 6]
for x in nom:
    print(nom)
    nom.pop(1)
print(nom)

I expected to get 1 printed at the end , but what I got is:

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

As the loop seems interrupted in midway. Why is that? please explain.

  • What's the error you get when the loop gets interrupted? – Aziz Sonawalla Nov 11 '20 at 20:49
  • You should not modify a list as you are iterating over it. Please see the linked questions with more detailed explanations. – Cory Kramer Nov 11 '20 at 20:50
  • In addition to the linked ones above, see: https://stackoverflow.com/questions/10665591/how-to-remove-list-elements-in-a-for-loop-in-python – Niko Föhr Nov 11 '20 at 20:53
  • @CoryKramer Thank you very much. This line cleared my confusion "You should not modify a list as you are iterating over it". I executed the program by iterating over other list. – SUBHRA Jatua Nov 12 '20 at 08:34

0 Answers0