Why do I get this many iterations when adding to and removing from a set while iterating over it?

后端 未结 4 1604
忘了有多久
忘了有多久 2021-02-03 16:29

Trying to understand the Python for-loop, I thought this would give the result {1} for one iteration, or just get stuck in an infinite loop, depending on if it does

4条回答
  •  感情败类
    2021-02-03 17:16

    I believe this has got something to do with the actual implementation of sets in python. Sets use hash tables for storing their items and so iterating over a set means iterating over the rows of its hash table.

    As you iterate and add items to your set, new hashes are being created and appended to the hash table until you reach number 16. At this point, the next number is actually added to the beginning of the hash table and not to the end. And since you already iterated over the first row of the table, the iteration loop ends.

    My answer is based on this one of a similar question, it actually shows this exact same example. I really recommend reading it for more detail.

提交回复
热议问题