Is there a a better way to remove the last N elements of a list.
for i in range(0,n): lst.pop( )
Using del The del operator deletes the element at the specified index location from the list. To delete the last element, we can use the negative index -1.
Python3. Method 3: Using pop() method: the pop() method will remove the last element from the list, So to remove last k elements from the python list, we need to perform the pop() operation k times.
pop() function. The simplest approach is to use the list's pop([i]) function, which removes an element present at the specified position in the list. If we don't specify any index, pop() removes and returns the last element in the list.
Works for n >= 1
>>> L = [1,2,3, 4, 5] >>> n=2 >>> del L[-n:] >>> L [1, 2, 3]
if you wish to remove the last n elements, in other words, keep first len - n elements:
lst = lst[:len(lst)-n]
Note: This is not an in memory operation. It would create a shallow copy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With