Is there a a better way to remove the last N elements of a list.
for i in range(0,n):
lst.pop( )
I see this was asked a long ago, but none of the answers did it for me; what if we want to get a list without the last N elements, but keep the original one: you just do list[:-n]
. If you need to handle cases where n
may equal 0
, you do list[:-n or None]
.
>>> a = [1,2,3,4,5,6,7]
>>> b = a[:-4]
>>> b
[1, 2, 3]
>>> a
[1, 1, 2, 3, 4, 5, 7]
As simple as that.