In this tutorial, we will learn how to get the last N elements of a list in Python using various methods. This technique is commonly used in many different programming tasks, ranging from analyzing data to creating custom iterators.
By the end of this tutorial, you will have a solid understanding of how to extract a specified number of items from the end of a Python list.
Step 1: Using Negative Indexing
Python allows negative indexing in lists, which means you can access the elements from the end of the list by providing a negative index value. To get the last N elements of a list, simply use the slice notation with the -N
index.
Let’s start by creating a sample list:
1 |
a_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
Now, let’s get the last 3 elements of our list using negative indexing:
1 2 |
n = 3 last_n_elements = a_list[-n:] |
The output will be:
[7, 8, 9]
Step 2: Using List Length
Another approach to get the last N elements of a list is to first find the length of the list using the len()
function. Then, subtract N from the length to compute the starting index for slicing the list.
Here’s an example:
1 2 3 |
list_length = len(a_list) start_index = list_length - n last_n_elements = a_list[start_index:] |
The output will be:
[7, 8, 9]
Step 3: Using itertools
The Python itertools library offers a set of fast, memory-efficient tools for handling iterators, which include functions for extracting the last N items of an iterable. The itertools.islice()
function can be used to get the last N elements of a list when combined with the itertools.count()
function.
Let’s see how to use itertools to extract the last N elements of a list:
1 2 3 4 |
import itertools counter = itertools.count(len(a_list) - n) last_n_elements = list(itertools.islice(a_list, next(counter), None)) |
This will give us the output:
[7, 8, 9]
Full Code
Here is the complete code discussed in this tutorial:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
a_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Using negative indexing n = 3 last_n_elements_negative_index = a_list[-n:] print(last_n_elements_negative_index) # Using list length list_length = len(a_list) start_index = list_length - n last_n_elements_length = a_list[start_index:] print(last_n_elements_length) # Using itertools import itertools counter = itertools.count(len(a_list) - n) last_n_elements_itertools = list(itertools.islice(a_list, next(counter), None)) print(last_n_elements_itertools) |
The output will be:
[7, 8, 9] [7, 8, 9] [7, 8, 9]
Conclusion
In this tutorial, we’ve learned different ways to get the last N elements of a list in Python: using negative indexing, list length, and the itertools library. Each method is efficient and helpful in various situations depending on your needs.
Now you know how to extract specific elements from the end of a list in Python, and you can apply this knowledge to various programming tasks.