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

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

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
Was this helpful?
Project

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup
Details
Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

Ā© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms