Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

python - Dictionary infinite loop is exiting unexpectedly

I was experimenting with various ways of creating an infinite loop in Python (other than the usual while True), and came up with this idea:

x = {0: None}

for i in x:
    del x[i]
    x[i+1] = None  # Value doesn't matter, so I set it to None
    print(i)

On paper, I traced out the way this would infinitely loop:

  1. I loop through the key's value in the dictionary
  2. I delete that entry.
  3. The current counter position in the loop + 1 will be the new key with value None which updates the dictionary.
  4. I output the current counter.

This, in my head, should output the natural numbers in a sort of infinite loop fashion:

0
1
2
3
4
5
.
.
.

I thought this idea was clever, however when I run it on Python 3.6, it outputs:

0
1
2
3
4

Yes, it somehow stopped after 5 iterations. Clearly, there is no base condition or sentinel value in the code block of the loop, so why is Python only running this code 5 times?

question from:https://stackoverflow.com/questions/54316557/dictionary-infinite-loop-is-exiting-unexpectedly

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no guarantee that you will iterate over all your dict entries if you mutate it in your loop. From the docs:

Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.

You could create an "enumerated" infinite loop similar to your initial attempt using itertools.count(). For example:

from itertools import count

for i in count():
    print(i)
    # don't run this without some mechanism to break the loop, i.e.
    # if i == 10:
    #     break

# OUTPUT
# 0
# 1
# 2
# ...and so on

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...