It seems so "dirty" emptying a list in this way:
while len(alist) > 0 : alist.pop()
Does a clear way exist to do that?
It seems so "dirty" emptying a list in this way:
while len(alist) > 0 : alist.pop()
Does a clear way exist to do that?
list = []
will reset list to an empty list.
Note that you generally should not shadow reserved function names, such as list, which is the constructor for a list object -- you could use lst or list_ instead, for instance.
This actually removes the contents from the list, not replaces the old label with a new empty list
del l[:]
example:
l1 = [1, 2, 3]
l2 = l1
del l1[:]
print(l2)
For the sake of completeness, slice assignment achieves the same effect:
l[:] = []
and can be used to shrink a part of the list while replacing a part at the same time (but is out of scope of the question).
Note that doing l = [] does not empty the list, just creates a new object and binds it to the variable l, but the old list will still have the same elements, and effect will be apparent if it had other variable bindings.
You could try:
alist[:] = []
Which means: Splice in the list [] (0 elements) at the location [:] (all indexes from start to finish)
The [:] is the slice operator. See this question for more information.