Is there a a better way to remove the last N elements of a list.
for i in range(0,n):
lst.pop( )
As Vincenzooo correctly says, the pythonic lst[:-n]
does not work when n==0
.
The following works for all n>=0
:
lst = lst[:-n or None]
I like this solution because it is kind of readable in English too: "return a slice omitting the last n elements or none (if none needs to be omitted)".
This solution works because of the following:
x or y
evaluates to x
when x
is logically true (e.g., when it is not 0
, ""
, False
, None
, ...) and to y
otherwise. So -n or None
is -n
when n!=0
and None
when n==0
.None
is equivalent to omitting the value, so lst[:None]
is the same as lst[:]
(see here).As noted by @swK, this solution creates a new list (but immediately discards the old one unless it's referenced elsewhere) rather than editing the original one. This is often not a problem in terms of performance as creating a new list in one go is often faster than removing one element at the time (unless n
<<len(lst)
). It is also often not a problem in terms of space as usually the members of the list take more space than the list itself (unless it's a list of small objects like bytes
or the list has many duplicated entries). Please also note that this solution is not exactly equivalent to the OP's: if the original list is referenced by other variables, this solution will not modify (shorten) the other copies unlike in the OP's code.
A possible solution (in the same style as my original one) that works for n>=0
but: a) does not create a copy of the list; and b) also affects other references to the same list, could be the following:
lst[-n:n and None] = []
This is definitely not readable and should not be used. Actually, even my original solution requires too much understanding of the language to be quickly read and univocally understood by everyone. I wouldn't use either in any real code and I think the best solution is that by @wonder.mice: a[len(a)-n:] = []
.