The Python Oracle

Different ways of clearing lists

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor

--

Chapters
00:00 Different Ways Of Clearing Lists
00:19 Accepted Answer Score 386
00:44 Answer 2 Score 13
01:01 Answer 3 Score 38
01:14 Answer 4 Score 10
01:25 Thank you

--

Full question
https://stackoverflow.com/questions/8507...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list

#avk47



ACCEPTED ANSWER

Score 386


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[:] = []



ANSWER 2

Score 38


There is a very simple way to clear a python list. Use del list_name[:].

For example:

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]
>>> print a, b
[] []



ANSWER 3

Score 13


It appears to me that del will give you the memory back, while assigning a new list will make the old one be deleted only when the gc runs.matter.

This may be useful for large lists, but for small list it should be negligible.

Edit: As Algorias, it doesn't matter.

Note that

del old_list[ 0:len(old_list) ]

is equivalent to

del old_list[:]



ANSWER 4

Score 10


del list[:] 

Will delete the values of that list variable

del list

Will delete the variable itself from memory