Different ways of clearing lists
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Track title: CC H Dvoks String Quartet No 12 Ame
--
Chapters
00:00 Question
00:27 Accepted answer (Score 384)
01:01 Answer 2 (Score 73)
01:44 Answer 3 (Score 38)
02:03 Answer 4 (Score 13)
02:26 Thank you
--
Full question
https://stackoverflow.com/questions/8507...
Answer 1 links:
[Mutable Sequence Types]: https://docs.python.org/dev/library/stdt...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list
#avk47
--
Track title: CC H Dvoks String Quartet No 12 Ame
--
Chapters
00:00 Question
00:27 Accepted answer (Score 384)
01:01 Answer 2 (Score 73)
01:44 Answer 3 (Score 38)
02:03 Answer 4 (Score 13)
02:26 Thank you
--
Full question
https://stackoverflow.com/questions/8507...
Answer 1 links:
[Mutable Sequence Types]: https://docs.python.org/dev/library/stdt...
--
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