Skip to content

Python last n elements of list

  • by

You can use slice notation to get the last n elements of a list in Python. Simple use the slicing syntax [ ] by passing a -n: as an argument to it.

Python last n elements of the list

A simple example code getting the last two elements of ["a", "b", "c"] results in ["b", "c"].

a_list = ["a", "b", "c"]

# Retrieve last 2 elements of list
last_n = a_list[-2:]
print(last_n)

# last 2 elements of list
test_list = [4, 5, 2, 6, 7, 8, 10]
res = test_list[-2:]
print(res)

Output:

Python last n elements of the list

Using islice() + reversed()

from itertools import islice

test_list = [4, 5, 2, 6, 7, 8, 10]
N = 5
res = list(islice(reversed(test_list), 0, N))
res.reverse()

print("The last N elements of list are : " + str(res))

Output: The last N elements of the list are : [2, 6, 7, 8, 10]

Note: if the list has fewer than n elements, this approach will return the entire list. If you want to handle such cases differently, you may want to add a check for the length of the list.

Comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *