Re: Question about idioms for clearing a list
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Question about idioms for clearing a list

From: Diez B. Roggisch <deets@nospam.web.de>
Date: Tue Jan 31 2006 - 19:16:14 CET

Steven Watanabe wrote:

> I know that the standard idioms for clearing a list are:
>
> (1) mylist[:] = []
> (2) del mylist[:]
>
> I guess I'm not in the "slicing frame of mind", as someone put it, but
> can someone explain what the difference is between these and:
>
> (3) mylist = []
>
> Why are (1) and (2) preferred? I think the first two are changing the
> list in-place, but why is that better? Isn't the end result the same?

No. Consider this simple example:

class Foo(object):
   def __init__(self, all_my_thingies):
       self.all_my_thingies = all_my_thingies

things = [1,2,3,4,5]

f = Foo(things)

things = [] # I've been robbed

print f.all_my_thingies # or not?

The reason is that l = [] just rebinds a new object (a list, but it could be
anything) to a name, while l[:] = [] will alter the object _referred_ to by
l. That is a HUGE difference!

Diez
Received on Tue Feb 7 20:25:02 2006