How To Get Last N Elements Of A List In Python

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:

Now, let’s get the last 3 elements of our list using negative indexing:

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:

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:

This will give us the output:

[7, 8, 9]

Full Code

Here is the complete code discussed in this tutorial:

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.