Question about idioms for clearing a list

Xavier Morel xavier.morel at masklinn.net
Tue Jan 31 16:17:37 EST 2006


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?
> 
> Thanks in advance.
> --
> Steven.

The solution (1) and (2) clear the content of the list (replace the 
content of the list by an empty list for (1), or delete the content of 
the list for (2) while the solution (3) creates a new list and binds the 
old name to the new list. This means that you don't actually modify 
(clear) the initial list.

Just try it out:

 >>> a = range(10)
 >>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> b = a
 >>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> c = a
 >>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> a.append(10) # assert that a, b and c point to the same list
 >>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 >>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 >>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 >>> b = []
 >>> b
[]
 >>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 >>> del c[:]
 >>> c
[]
 >>> a
[]
 >>>

Here we can see that using method (3) on b didn't modify the content of 
a (even though we asserted that they were the same list).
Using method (2) on c, the other hand, did modify the content of a.

This is because method (3) on b actually created a new list and bound 
"b" (as a name) to that new list, without modifying the list "b" used to 
be bound to (which is the one "a" and "c" are still bound to).



More information about the Python-list mailing list