Python List - Get Last N Elements
Python List - Get last N elements
To get the last N elements of a list in Python, you can use negative indexing and slicing.
For example, if my_list is a given list of elements, then the syntax of the expression to get the last N elements in the list my_list is
my_list[-N:]
The negative index count from end of the list. Therefore [-N:] specifies the last N elements.
In this tutorial, you will learn how to get the last N elements in a given list, with examples.
Examples
The following are some of the examples, where we take a list of elements, and get the last N elements from the list using index.
1. Get the last 5 elements in the given list of integers in Python
In this example, we take a list of integer values, and get the last 5 elements in the list, and print it to standard output.
Python Program
my_list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
N = 5
last_n_elements = my_list[-N:]
print(f"Last N elements : {last_n_elements}")
Output
Last N elements : [12, 14, 16, 18, 20]
Explanation
2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ← list elements
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 ← negative index values
↑________________↑
last 5 elements
12, 14, 16, 18, 20
2. Get the last 5 elements in the list when length of list is 3
In this example, we take a list of string values, and get the last 5 elements in the list. But the twist here is that the N value is greater than the number of elements in the list.
Python Program
my_list = ["apple", "banana", "cherry"]
N = 5
last_n_elements = my_list[-N:]
print(f"Last N elements : {last_n_elements}")
Output
Last N elements : ['apple', 'banana', 'cherry']
If the -N exceeds the indices of the elements in the list, Python does not raise any exception, instead it considers the starting of the list.
Summary
In this Python Lists tutorial, we have seen how to get the last N elements of the given list using slicing.