Python: Get Last N Elements from List/Array

# Python: Get Last N Elements from List/Array

Array manipulation and element retrieval is a common task among any programming language, and luckily Python has some useful syntax for easily retrieving elements from various positions in the list.

One common use case is to retrieve N elements from the end of a list/array, which we'll show how to do here.

### Background: Python Array Syntax

In Python, you can retrieve elements using similar syntax as in many other languages, using brackets ([]) and an index. However, this syntax can be extended to optionally specify both a starting and ending index. By providing both indexes, you can retrieve a range of elements:

>>> arr = [1, 2, 3, 4, 5, 6]
>>> arr[2:4]
[3, 4]


What if you omitted the ending index? In that case, Python will automatically assume you want to retrieve elements from the starting index to the end of the list.

>>> arr = [1, 2, 3, 4, 5, 6]
>>> arr[2:]
[3, 4, 5, 6]


## Get free courses, guided projects, and more

The indexes can also be negative, which specifies the element index from the end of the list.

>>> arr = [1, 2, 3, 4, 5, 6]
>>> arr[-2]
5


### Last N Elements

Using this knowledge we have of accessing multiple elements from the end of the list, we can then figure out how to access the last N elements. To do so, simply use the syntax [-N:], where N is the number of elements you want to access:

>>> arr = [1, 2, 3, 4, 5, 6]
>>> arr[-2:]
[5, 6]


We can also use variables to specify how many elements to retrieve:

>>> arr = [1, 2, 3, 4, 5, 6]
>>> n = 3
>>> arr[-n:]
[4, 5, 6]


Using either of these methods you can retrieve the last N elements of a list/array in Python.

Last Updated: July 17th, 2022
Project

### Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
Details
Project

### Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

Details