Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the last N elements of a list

Tags:

python

list

Is there a a better way to remove the last N elements of a list.

for i in range(0,n):     lst.pop( ) 
like image 763
Theo Avatar asked Mar 30 '13 06:03

Theo


People also ask

How do I remove the last 10 elements from a list in Python?

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.

How do I remove the last 3 elements from a list in Python?

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.

How do I remove the last few elements from a list in Python?

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.


2 Answers

Works for n >= 1

>>> L = [1,2,3, 4, 5] >>> n=2 >>> del L[-n:] >>> L [1, 2, 3] 
like image 187
jamylak Avatar answered Sep 26 '22 06:09

jamylak


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.

like image 42
karthikr Avatar answered Sep 26 '22 06:09

karthikr