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

后端 未结 4 1659
忘了有多久
忘了有多久 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:15

    From the python 3 documentation:

    Code that modifies a collection while iterating over that same collection can be tricky to get right. Instead, it is usually more straight-forward to loop over a copy of the collection or to create a new collection:

    Iterate over a copy

    s = {0}
    s2 = s.copy()
    for i in s2:
         s.add(i + 1)
         s.remove(i)
    

    which should iterate only 1 time

    >>> print(s)
    {1}
    >>> print(s2)
    {0}
    

    Edit: A Possible reason for this iteration is because a set is unordered, causing some kind of stack trace sort of thing. If you do it with a list and not a set, then it will just end, with s = [1] because lists are ordered so the for loop will start with index 0 and then move on to the next index, finding that there isn't one, and exiting the loop.

提交回复
热议问题