Open In App

Remove last K elements of list – Python

Last Updated : 18 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a list and an integer K, the task is to remove the last K elements from the list. For example, if the list is [1, 2, 3, 4, 5] and K = 2, the result should be [1, 2, 3].

Let’s explore different methods to remove the last K elements from a list in Python.

Using list slicing

List slicing is one of the most efficient and simplest ways to remove the last K elements from a list. With this method, we can easily create a new list that contains all the elements except for the last K elements.

Python
a = [1, 2, 3, 4, 5]
k = 2
res = a[:-k] if k else a
print(res)  

Output
[1, 2, 3]

Explanation:

  • List slicing allows us to select a portion of the list based on indices.
  • a[:-k] takes all elements from the start of the list to the K-th last element, effectively removing the last K elements.
  • If K is zero, it returns the original list without modification.

Let’s explore some more methods and see how we can remove the last K elements from a list.

Using list.pop()

Another approach is to use the pop() method. This method removes the last element from the list. By calling pop() in a loop K times, we can remove the last K elements from the list.

Python
a = [1, 2, 3, 4, 5]
k = 2
for _ in range(k):
    a.pop()
print(a) 

Output
[1, 2, 3]

Explanation:

  • pop() method removes the last element from the list.
  • By using a loop and calling pop() K times, we can effectively remove the last K elements.
  • This method modifies the list in place repeatedly.

Using del()

del() statement allows us to remove elements from a list by specifying an index range. This method works by deleting elements in place without creating a new list.

Python
a = [1, 2, 3, 4, 5]
k = 2
del a[-k:]
print(a)  

Output
[1, 2, 3]

Explanation:

  • del a[-k:] deletes the last K elements from the list in place.
  • It directly modifies the list and doesn’t create a new one.
  • This method is more efficient than using pop() in a loop but less concise than slicing.

Using list.remove()

remove() method searches for an element to remove, and since we want to remove the last K elements, we would call remove() K times, each time on the last element of the list.

Python
a = [1, 2, 3, 4, 5]
k = 2
for _ in range(k):
    a.remove(a[-1])
print(a)  

Output
[1, 2, 3]

Explanation:

  • remove() method removes the first occurrence of the specified element from the list.
  • In this case, we use remove(a[-1]) to remove the last element from the list by passing the last element explicitly.


Next Article

Similar Reads