Get the Last N Elements of a List in Python
In Python, you can retrieve the last N elements of a list using slicing, the deque from the collections module, or loops. The most efficient way is to use negative indexing with slicing: my_list[-N:]. Below, we explore multiple ways to achieve this.
Examples
1. Get the Last N Elements Using List Slicing
The most straightforward way to get the last N elements of a list is by using slicing with a negative index.
# Sample list
numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# Getting the last 3 elements
last_three = numbers[-3:]
# Printing the result
print("Last 3 elements:", last_three)
Explanation:
numbersis a list containing 10 integer elements.- The slicing operation
numbers[-3:]selects the last three elements of the list. - Negative indexing allows us to count elements from the end of the list.
Output:
Last 3 elements: [80, 90, 100]
2. Get the Last N Elements Using the collections.deque Method
If you are working with large lists and need an efficient way to get the last N elements, you can use deque from the collections module.
from collections import deque
# Sample list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Getting the last 4 elements efficiently
last_four = deque(numbers, maxlen=4)
# Converting deque to list
result = list(last_four)
# Printing the result
print("Last 4 elements:", result)
Explanation:
deque()is initialized with the list and a fixed size usingmaxlen=4.- It automatically retains only the last
Nelements, discarding earlier ones. - Converting
dequeback to a list gives us the last 4 elements efficiently.
Output:
Last 4 elements: [7, 8, 9, 10]
3. Get the Last N Elements Using a Loop
If slicing is not an option, a simple loop can extract the last N elements from a list.
# Sample list
colors = ["red", "blue", "green", "yellow", "purple", "orange"]
# Number of elements to get
N = 3
# Extracting the last N elements using a loop
last_colors = []
for i in range(len(colors) - N, len(colors)):
last_colors.append(colors[i])
# Printing the result
print("Last 3 colors:", last_colors)
Explanation:
len(colors) - Ncalculates the starting index of the lastNelements.- The for loop iterates from that index to the end of the list.
- Each element is appended to
last_colors, creating the result.
Output:
Last 3 colors: ['yellow', 'purple', 'orange']
4. Get the Last N Elements Using enumerate() with List Comprehension
Another method to retrieve the last N elements is using enumerate() with list comprehension.
# Sample list
scores = [88, 76, 92, 85, 91, 78, 95, 89]
# Number of elements to retrieve
N = 5
# Using list comprehension with enumerate
last_scores = [score for index, score in enumerate(scores) if index >= len(scores) - N]
# Printing the result
print("Last 5 scores:", last_scores)
Explanation:
enumerate(scores)provides index-value pairs.- The condition
index >= len(scores) - Nensures only the lastNelements are added. - This method is an alternative to slicing when more control is needed.
Output:
Last 5 scores: [92, 85, 91, 78, 95]
Conclusion
Python provides multiple ways to get the last N elements from a list:
- List Slicing (
-N:): The most efficient method for general use. collections.deque: Best for large lists where performance matters.- Loop Method: Useful when slicing is not available.
enumerate()with List Comprehension: Provides conditional control.
