(Extracted from another question.) Removing this set's 200,000 elements one by one like this takes 30 seconds (Attempt This Online!):
s = set(range(200000))
while s:
for x in s:
s.remove(x)
break
Why is that so slow? Removing a set element is supposed to be fast.
I think this is happening because you are removing the first element in the set every time. This creates a set which is increasingly empty one each iteration, so each time you create a new iterator and call
__next__, it has to search further and further away.So, here is the source code for the iterator
__next__It has to find the next entry like this:
The the iterator
__next__works by finding the first non-empty, non-dummy value:So, say we have something like:
Then on each iteration of the
whileloop, you get:So each time, the iterator has to search further and further away from the beginning of the entires, since each iteration of the while loop removes the first one. Hence, the quadratic time behavior.