[Tutor] Re: Unexpected results with list

don arnold darnold02 at sprynet.com
Thu Jan 29 21:35:59 EST 2004


----- Original Message -----
From: "Michael Long" <mlong at datalong.com>
To: <Tutor at Python.Org>
Sent: Thursday, January 29, 2004 7:03 PM
Subject: Re: [Tutor] Re: Unexpected results with list


<snip>
>
> I have found the offending code but do not understand what is going on.
When you
> run the following snippet it only print '150003' and '150005'. I would be
grateful
> for an explaination of this behavior.
>
> newKeyRS = ['150003', '150004', '150005', '150006', '15007', '15008']
>
> for newRecord in newKeyRS:
>         if newRecord.startswith('15000'): print newRecord
>         newKeyRS.remove(newRecord)

The problem here is that you're modifying the list as you iterate over it.
That's a no-no. Iterate over a copy of the list, instead (created here
through slicing):

newKeyRS = ['150003', '150004', '150005', '150006', '15007', '15008']

for newRecord in newKeyRS[:]:     ## using slicing to create a shallow copy
of the list
        if newRecord.startswith('15000'): print newRecord
        newKeyRS.remove(newRecord)
>>>
150003
150004
150005
150006

HTH,
Don




More information about the Tutor mailing list