This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author rhettinger
Recipients docs@python, r.david.murray, rhettinger, terry.reedy, the_darklord
Date 2017-09-24.18:00:27
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1506276027.87.0.411782599397.issue30826@psf.upfronthosting.co.za>
In-reply-to
Content
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
History
Date User Action Args
2017-09-24 18:00:27rhettingersetrecipients: + rhettinger, terry.reedy, r.david.murray, docs@python, the_darklord
2017-09-24 18:00:27rhettingersetmessageid: <1506276027.87.0.411782599397.issue30826@psf.upfronthosting.co.za>
2017-09-24 18:00:27rhettingerlinkissue30826 messages
2017-09-24 18:00:27rhettingercreate