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: Tim Chase <python.list@tim.thechases.com>
Date: Tue Jan 31 2006 - 18:18:49 CET

> 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?

A little example will demonstrate:

>>> x = [1,2,3,4,5]
>>> y = x
>>> z = x
>>> x = []
>>> y
        [1, 2, 3, 4, 5]
* >>> z
        [1, 2, 3, 4, 5]
>>> y[:]=[]
* >>> z
        []

[*] note the differences in the results of "z", even though we've
never touched "z" explicitly

By using

        x = []

you set x, but you do not clear the list that other items (y & z)
reference. If you use either of the two idioms you describe, you
effect all items that reference that list.

-tim
Received on Tue Feb 7 20:24:11 2006