for i in list - change a list inside a for loop?

Jp Calderone exarkun at intarweb.us
Sat Mar 1 13:51:12 EST 2003


On Sat, Mar 01, 2003 at 07:37:03PM +0100, Klaus Meyer wrote:
> Hi,
> 
> it is OK to change a list inside a for loop?
> Example:
> 
> x=range(100)
> for i in x:
>    del x[-1]
> 

 Nope.  This is Bad.  Same goes for most mutable types, you shouldn't change
them while you're iterating over them.

> 
> Another Question:
> How to remove a found element from a list in a for-loop?
> 
> x=["A", "B", "C", "D"]
> for i in x:
> 	if i=="C": del x[this one, but how?]
> 

    for i in range(len(x) - 1, -1, -1):
        if x[i] == "C":
            del x[i]


  Iterating backwards prevents the indices from being kicked out of sync
when you delete an element (try it going forward if you don't see why this
might be a problem).

  Iterating over the indices of the list lets you know where you are at
all times, but it can be slightly less convenient.  You could iterate over
indices and values...

    rev_x = x[:]
    rev_x.reverse()
    for (i, v) in zip(range(len(x) - 1, -1, -1), rev_x):
        if v == "C":
            del x[i]

  In 2.3, enumerate() has been added, but it only goes forward.  For lists,
you could solve this by...

    def rev_enumerate(sequence):
        rev_seq = sequence[:]
        rev_seq.reverse()
        return enumerate(rev_seq)

  As you can see, this is just a simple abstraction of the previous example.

  Jp

--
http://catandgirl.com/view.cgi?44
-- 
 up 20 days, 22:29, 4 users, load average: 0.45, 0.27, 0.26
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20030301/351eb3f8/attachment.sig>


More information about the Python-list mailing list