![]() |
VOOZH | about |
This article discusses ways to fetch the last N elements of a list in Python.
Example: Using list Slicing
[2, 6, 7, 8, 10]
Explaination: This problem can be performed in 1 line rather than using a loop using the list-slicing functionality provided by Python. Minus operator specifies slicing to be done from the rear end.
Table of Content
Let's discuss certain solutions to perform this task.
The inbuilt islice() functions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end.
The last N elements of list are : [2, 6, 7, 8, 10]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list
This code extracts the last N elements from a list. It first reverses the list using slicing ([::-1]), then iterates over the first N elements, appending them to a new list res. Finally, it reverses res to restore the original order and prints the last N elements.
The last N elements of list are : [2, 6, 7, 8, 10]
You can define a generator function that yields the last N elements of a list.
The last N elements of list are : [[2, 6, 7, 8, 10]]
Time Complexity : O(N)
Auxiliary Space : O(1)