strange behaviour with remove

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Sat Jun 19 13:10:20 CEST 2004


Panard wrote:
> Ok, I reply to myself, it's working when you add, line 3
> l = [ i for i in l ]
> 
> I think the reason is that when you do a remove on d[ 'list' ] it will also
> do a remove on l, because, I think, l in the dictionnary is only a
> reference...

You're partially right. The list referenced to by d['list'] is the same
object as the list referenced to by l (to verify this, do a "print
d['list'] is l"). The main reason that your loop does not work is that
it modifying a list you are iterating over leads to undefined behavior.

In your solution above, you are assigning a new list to the name "l",
iterate over this list, and remove from the original list which is now
only referenced by d['list']. This is the common solution for the
problem, although there is an easier way to copy a list:

l = l[:]

Reinhold

-- 
Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
mitbrächte, wäre das bedauerlich.  Was bei Windows der Umfang eines
"kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
  -- David Kastrup in de.comp.os.unix.linux.misc



More information about the Python-list mailing list