[Tutor] Re: Unexpected results with list

Alan Gauld alan.gauld at blueyonder.co.uk
Fri Jan 30 03:50:41 EST 2004


> newKeyRS = ['150003', '150004', '150005', '150006', '15007',
'15008']
>
> for newRecord in newKeyRS:
>         if newRecord.startswith('15000'): print newRecord
>         newKeyRS.remove(newRecord)

When you remove an item everything shuffles up, in effect.
Thus when the for loop pulls out the next item it effectively
misses one out!

BUT You are deleting every record! I assume you really only
want to remove the ones you filter?  ie the remove should be
inside the loop?

For this kind of thing you could use a while
loop with index:

index = 0
while index < len(newKeyRS):
         if newRecord.startswith('15000'): print newRecord
             newKeyRS.remove(newRecord)  # don't incr index
         else: index += 1

Or better still use the filter function to remove the unwanted
ones:

newKeyRS = filter(lambda x: not x.startswith('15000'), newKeyRS)

Or if you prefer, a list comprehension:

newKeyRS = [ item for item in newKeyRS if not
item.startswith('15000')]

Personally I'd use filter for this because its more self
explanatory, but if its a big list a comprehensuon will
probably be faster.

Alan G.








More information about the Tutor mailing list