Entry
How do I empty a list?
May 10th, 2006 14:41
stephen brown, Jonathan Schroder, Michael Chermside, Asher Amoretto,
Although there are other methods, the standard idiom looks like this:
>>> aBigList = range(20)
>>> del aBigList[:]
>>> aBigList
[]
That funny-looking [:] thing is not a sideways view of a fellow peeking
through a window... it's a slice operator. "aBigList[2:5]" means all
items in aBigList starting with item #2 and ending just before item #5
(so it's items 2, 3, and 4). Either boundary can be ommitted,
so "aBigList[:5]" means all items from the start of the list up to just
before #5, and "aBigList[2:]" means all items from #2 through the end
of the list. "aBigList[:]" means all items from the start to the end.
So "del aBigList[:]" clears the entire list.
____________________________________
why not yourlist = [] ?
____________________________________
Because yourlist = [] doesn't empty the existing list, it just makes
yourlist a reference to a different list. The distinction only matters
if you have multiple references to the same list (which isn't uncommon.)
>>> a = range(5)
>>> b = a
Because python uses references, a and b are now references to the same
list. This can be proven by changing one of them.
>>> a[2] = 'a'
>>> b
[0, 1, 'a', 3, 4]
>>>
Re-assigning a makes it refer to a different list, but doesn't
change the list that it used to refer to.
>>> a = []
>>> b
[0, 1, 'a', 3, 4]
>>>
If you want to change the object, not just the name, you need to use
the del operator.
>>> a = b
>>> a
[0, 1, 'a', 3, 4]
>>> del b[:]
>>> a
[]
>>>
Admittedly, the distinction gets confusing when the slice notation is
used on the left-hand-side of the assignment.
>>> a = range(5)
>>> b = a
>>> a[:] = []
>>> b
[]
>>>