0
x = {0: None}
for i in x:
    del x[i]
    x[i+1] = None
    print(i)

This code on execution gives the output as

0
1
2
3
4

By the logic of the loop it seems it should either go on forever or give an error when the dictionary becomes zero. But neither happens. Can someone explain how? I'm running it in python 3.6

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 4
    TL;DR: you get weird effects if you manipulate the structure you’re iterating over. What effect exactly it will have depends on the implementation details. Just don’t expect any particular behavior and just don’t do it. – deceze Aug 23 '20 at 08:49
  • 1
    And [here](https://github.com/satwikkansal/wtfpython#-modifying-a-dictionary-while-iterating-over-it) is the explanation of the **exact** same code. – Asocia Aug 23 '20 at 08:52
  • I see. This is definitely not a practice I'm doing. I was trying some things out with dictionaries. I understand the issue now though. Thank you. – CuriousProgrammer69 Aug 23 '20 at 09:01

0 Answers0