a bug in list.remove?

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Fri Aug 18 14:52:07 EDT 2006


Astan Chee:

(This is a small trap of Python, that it shares with some other
languages, and it shows that it may exist a language with a higher
level than Python.)
Generally in Python you can't modify a sequence that you are iterating
on.
There are some ways to avoid the problem. You can create a duplicate of
the ps list:

ps = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
qs = [6,7,8,9,10,11,12,1,2]

for p in ps[:]:
    if p in qs:
        ps.remove(p)
print ps

Or:

for p in list(ps):
    if p in qs:
        ps.remove(p)
print ps

Or:

import copy
for p in copy.copy(ps):
    if p in qs:
        ps.remove(p)
print ps

Or you can adopt a different strategy:

print [el for el in ps if p not in qs]

This algorithm is O(n*m), so if the two lists are long, you may need
too much time to run that. To speed up the program you can do this
(Python 2.4):

sqs = set(qs)
print [el for el in ps if p not in sqs]

Bye,
bearophile




More information about the Python-list mailing list