[Tutor] Re: Unexpected results with list
mlong at datalong.com
Thu Jan 29 22:29:46 EST 2004
>> 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
>> for an explaination of this behavior.
>> newKeyRS = ['150003', '150004', '150005', '150006', '15007', '15008']
>> for newRecord in newKeyRS:
>> if newRecord.startswith('15000'): print 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
This explains a lot of my frustration. Next time I will try to boil my question
down before posting it to the list. I realized after sending the first posting that
it really didn't make sense to anyone who had not been staring at my screen for a
number of hours. Actually it was Alan's reply that made the ambiquity of the
question clear :)
More information about the Tutor