Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #60697

For-each behavior while modifying a collection

Date 2013-11-28 16:49 +0100
Subject For-each behavior while modifying a collection
From Valentin Zahnd <v.zahnd@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.3360.1385653859.18130.python-list@python.org> (permalink)

Show all headers | View raw


Hello

For-each does not iterate ober all entries of collection, if one
removes elements during the iteration.

Example code:

def keepByValue(self, key=None, value=[]):
    for row in self.flows:
        if not row[key] in value:
            self.flows.remove(row)

It is clear why it behaves on that way. Every time one removes an
element, the length of the colleciton decreases by one while the
counter of the for each statement is not.
The questions are:
1. Why does the interprete not uses a copy of the collection to
iterate over it? Are there performance reasons?
2. Why is the counter for the iteration not modified?

Valentin

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

For-each behavior while modifying a collection Valentin Zahnd <v.zahnd@gmail.com> - 2013-11-28 16:49 +0100
  Re: For-each behavior while modifying a collection Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-11-29 03:22 +0000
    Re: For-each behavior while modifying a collection Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-11-29 11:37 -0500

csiph-web