How to empty a list
Say you have a list in your program and you are going to reuse the name of the list, or delete all items from the list (empty the list). One option is to delete the list completely along with the name :
Now, if you take some time to play in your Python interpreter, you will have a better idea what happens :
>>> li = [1, 2, 3, 4, 5]
>>> li2 = li
>>> li2
[1, 2, 3, 4, 5]
>>> del li[:]
>>> li
[]
>>> li2
[]
>>> li1 = [1, 3, 5]
>>> li3 = li1
>>> li3
[1, 3, 5]
>>> li1
[1, 3, 5]
>>> li1 = []
>>> li1
[]
>>> li3
[1, 3, 5]
>>> li4 = [1, 2]
>>> li5 = li4
>>> li5
[1, 2]
>>> del li4
>>> li4
Traceback (most recent call last):
File "", line 1, in
NameError: name 'li4' is not defined
>>> li5
[1, 2]
>>>
>>> del liAnother option is to delete all items inside the list:
>>> del li[:]Many of you can think of another alternative :
>>> li = []Though li = [], apparently it makes li empty, actually it is creating a new list object and the previous object will be in memory.
Now, if you take some time to play in your Python interpreter, you will have a better idea what happens :
>>> li = [1, 2, 3, 4, 5]
>>> li2 = li
>>> li2
[1, 2, 3, 4, 5]
>>> del li[:]
>>> li
[]
>>> li2
[]
>>> li1 = [1, 3, 5]
>>> li3 = li1
>>> li3
[1, 3, 5]
>>> li1
[1, 3, 5]
>>> li1 = []
>>> li1
[]
>>> li3
[1, 3, 5]
>>> li4 = [1, 2]
>>> li5 = li4
>>> li5
[1, 2]
>>> del li4
>>> li4
Traceback (most recent call last):
File "
NameError: name 'li4' is not defined
>>> li5
[1, 2]
>>>
Comments