magic_numbers
changed size during iteration27 magic_numbers.add(8)
28
29 for elem in magic_numbers:
30 magic_numbers.add(get_next(elem))31 return magic_numbers
Sets are represented by a hash table and adding or removing items while iterating over it will alter the iteration order.
This will cause a RuntimeError
.
If you need to modify the set during iteration, it is recommended to iterate over a [shallow copy]((https://docs.python.org/3/library/copy.html of the dictionary) of the set. A shallow copy creates a new object which stores the reference of the original elements.
For further reading, check
magic_numbers = {0, 1, 1, 2, 3, 5}
for elem in magic_numbers:
magic_numbers.add(get_next(elem)) # This will raise a `RuntimeError`.
magic_numbers = {0, 1, 1, 2, 3, 5}
for elem in magic_numbers.copy():
magic_numbers.add(get_next(elem))