Message302874
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 |
|
Date |
User |
Action |
Args |
2017-09-24 18:00:27 | rhettinger | set | recipients:
+ rhettinger, terry.reedy, r.david.murray, docs@python, the_darklord |
2017-09-24 18:00:27 | rhettinger | set | messageid: <1506276027.87.0.411782599397.issue30826@psf.upfronthosting.co.za> |
2017-09-24 18:00:27 | rhettinger | link | issue30826 messages |
2017-09-24 18:00:27 | rhettinger | create | |
|