If you're clearing the list, you, obviously, don't need the list anymore. If so, you can just delete the entire list by simple del method.
a = [1, 3, 5, 6]
del a # This will entirely delete a(the list).
But in case, you need it again, you can reinitialize it. Or just simply clear its elements by
del a[:]
There are two cases in which you might want to clear a list:
old_list
further in your code;In case 1 you just go on with the assigment:
old_list = [] # or whatever you want it to be equal to
In case 2 the del
statement would reduce the reference count to the list object the name old list
points at. If the list object is only pointed by the name old_list
at, the reference count would be 0, and the object would be freed for garbage collection.
del old_list
another solution that works fine is to create empty list as a reference empty list.
empt_list = []
for example you have a list as a_list = [1,2,3]
. To clear it just make the following:
a_list = list(empt_list)
this will make a_list
an empty list just like the empt_list
.
Doing alist = []
does not clear the list, just creates an empty list and binds it to the variable alist
. The old list will still exist if it had other variable bindings.
To actually clear a list in-place, you can use any of these ways:
alist.clear() # Python 3.3+, most obvious
del alist[:]
alist[:] = []
alist *= 0 # fastest
See the Mutable Sequence Types documentation page for more details.
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
[] []
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[:]
del list[:]
Will delete the values of that list variable
del list
Will delete the variable itself from memory
Source: Stackoverflow.com