Different ways of clearing lists

johannix picture johannix · May 12, 2009 · Viewed 346.1k times · Source

Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python?

old_list = []
old_list = list()

The reason I ask is that I just saw this in some running code:

del old_list[ 0:len(old_list) ]

Answer

Koba picture Koba · May 12, 2009

Clearing a list in place will affect all other references of the same list.

For example, this method doesn't affect other references:

>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]

But this one does:

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]      # equivalent to   del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True

You could also do:

>>> a[:] = []