2.3 list reverse() bug?
Alex Martelli
aleax at aleax.it
Fri Dec 26 08:14:24 EST 2003
Bjorn Pettersen wrote:
...
> There are of course times where a copy is needed (e.g. multi-version
> scenarios) but most programmers don't bump into these very frequently...
Here's my candidate for "most frequent scenario where copies are needed":
for item in somelist:
if froobable(item):
somelist.append(frooble(item))
elif uncadable(item):
somelist.remove(item)
i.e.: you want to modify the very list you're looping on. This is one
of Python's few but important "traps and pitfalls". The simplest fix:
for item in list(somelist):
...same as above...
list(x) is my favourite way to make a shallow copy of list x, but x[:]
and copy.copy(x) are essentially equivalent.
Alex
More information about the Python-list
mailing list