[docs] [issue30826] More details in reference 'Looping through a list in Python and modifying it'
Raymond Hettinger
report at bugs.python.org
Sun Sep 24 14:00:27 EDT 2017
Raymond Hettinger added the comment:
After looking at this again, I think the entire example should be removed. We really don't want to encourage people to code like this (it would never make it through a code review). The example itself is silly (not fully, just weird and lacking real-world motiviation). The s.insert(0,x) code is an anti-pattern. And in general, mutating a data structure while iterating over it is a perilous practice leading to fragile code (many data structures ban the practice outright: databases, deques, dicts).
Mutating while iterating is only safe if a data structure makes explicit guarantees about how it iterates. In Python, we have only a handful of such guarantees (you can safely mutate dict values while iterating over the keys and lists guarantee that the iterator looks-up consecutive indicies regardless of changes to the underlying list).
I propose to remove the last two paragraphs and the example, replacing them with clear practical advice and patterns that would pass a code review.
Something like this:
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.
# Strategy: Iterate over a copy
for user, status in users.copy():
if status == 'inactive':
del users[user]
# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status
----------
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue30826>
_______________________________________
More information about the docs
mailing list