Open In App

Python | Remove last K elements of list

Last Updated : 02 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

We often come to situations in which we need to decrease the size of the list by truncating the k last elements of the list. This has its application in the day-day programming when sometimes we require getting all the lists of similar size or removing the last few records from a list. Let’s discuss a few ways in which this task can be performed.

Using len() + list slicing to remove last K elements of list

List slicing can perform this particular task in which we just slice the first len(list) – K elements to be in the list and hence remove the last K elements.

Here we find the length of the current list and calculate the length that will be after removing the n elements (len_l – l), then using slicing, we create a copy list, where it has last n elements removed.

Python3




# initializing list 
test_list = [1, 4, 6, 3, 5, 8]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing K
K = 3
 
# using len() + list slicing
# remove last K elements
res = test_list[: len(test_list) - K]
 
# printing result
print ("The list after removing last K elements : " +  str(res))


Output

The original list is : [1, 4, 6, 3, 5, 8]
The list after removing last K elements : [1, 4, 6]

Time complexity: O(N).
Auxiliary space: O(N).

Using Negative list slicing to remove last K elements of list

We can perform this particular task using the negative list slicing, in which we start removing the elements from the last index of the list and hence remove all the K elements from the last. If the negative index value is more than the length of the list, it will return an empty list.

Python3




# initializing list
test_list = [1, 4, 6, 3, 5, 8]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 3
 
# using negative list slicing
# remove last K elements
res = test_list[:-K]
 
# printing result
print("The list after removing last K elements : " + str(res))


Output:

The original list is : [1, 4, 6, 3, 5, 8]
The list after removing last K elements : [1, 4, 6]

Time complexity: O(1), which means it runs in constant time, regardless of the size of the input list.
Auxiliary space: O(1), as it only requires a fixed amount of additional space to store the variable K, the sliced list res, and the string literals used for printing.

Using Python List pop() Method to remove last K elements of list

The pop() method will remove the last element from the list, So to remove the last k elements from the Python List, we need to perform the pop() operation k times.

Python3




# initializing list
test_list = [1, 7, 6, 3, 5, 8]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 3
 
# using pop()
# remove last K elements
for i in range(K):
    test_list.pop()
 
# we can also do list comprehension to pop()
# _ = [test_list.pop() for _ in range(K)]
 
# printing result
print("The list after removing last K elements : " + str(test_list))


Output:

The original list is : [1, 7, 6, 3, 5, 8]
The list after removing last K elements : [1, 7, 6]

Time complexity: O(K), where K is the number of elements removed from the end of the list. 

Auxiliary space complexity: O(1), as the algorithm only uses a constant amount of extra space, regardless of the size of the input list.

Using del keyword and list slicing to remove last K elements of list

Here we return a sliced range and delete it from the list using Python del keyword.

Python3




# initializing list
test_list = [1, 7, 6, 3, 5, 8]
# remove last 3 elements
K = 3
# using del on negative slicing
del test_list[-3:]
 
print("List after removing elements:", test_list)


Output:

List after removing elements: [1, 7, 6]

The time complexity of the given code is O(1) since we are only deleting the last three elements of the list, which can be done in constant time.

The auxiliary space complexity is also O(1) since we are not using any extra space or data structures to perform the operation.

Using itertools:

Another approach to remove the last k elements of a list is to use the itertools module’s islice function. The islice function returns an iterator that produces selected elements from the input iterator. We can use this function to create a new iterator that produces all elements of the list except for the last k elements, then use the list function to create a new list from the iterator.

Here is an example of how this can be done:

Python3




import itertools
 
# initializing list
test_list = [1, 4, 6, 3, 5, 8]
 
# printing original list
print("The original list is:", test_list)
 
# initializing K
K = 3
 
# using islice to remove last K elements
res = list(itertools.islice(test_list, 0, len(test_list)-K))
 
# printing result
print("The list after removing last K elements:", res)
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list is: [1, 4, 6, 3, 5, 8]
The list after removing last K elements: [1, 4, 6]

Time complexity: O(n), where n is the length of the list. This is because the islice function must iterate over all n elements of the input list in order to produce the desired output iterator. 
Auxiliary space: O(n).

 Using numpy.delete() function:

Approach:

First, we need to import the numpy library.
Next, we will create a numpy array from the given list using numpy.array().
We will then use numpy.delete() function to remove the last k elements of the array.
We will convert the resulting array back to a list using list() function.

Algorithm:
1. Import numpy library.
2. Initialize the list.
3. Initialize k.
4. Convert the list to a numpy array using numpy.array().
5. Use numpy.delete() to remove the last k elements of the array.
6. Convert the resulting array back to list using list() function.
7. Print the list.

Python3




# import numpy library
import numpy as np
 
# initialize list
test_list = [1, 4, 6, 3, 5, 8]
 
# initialize k
k = 3
 
# convert list to numpy array
arr = np.array(test_list)
 
# remove last k elements using numpy.delete()
new_arr = np.delete(arr, np.s_[-k:])
 
# convert numpy array back to list
res = list(new_arr)
 
# print the list
print("The list after removing last K elements : " + str(res))


Output:

The list after removing last K elements : [1, 4, 6]
 

Time complexity:

Creating a numpy array from the list takes O(N) time.
Removing the last k elements using numpy.delete() function takes O(K) time.
Converting the resulting array back to a list takes O(N) time.
Therefore, the overall time complexity is O(N+K).
Space complexity:

Creating a numpy array from the list takes O(N) space.
Removing the last k elements using numpy.delete() function takes O(K) space.
Converting the resulting array back to a list takes O(N) space.
Therefore, the overall space complexity is O(N+K).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads