Get last N elements from given list in Python


Given a Python list we want to find out only e e the last few elements.

With slicing

The number of positions to be extracted is given. Based on that we design is slicing technique to slice elements from the end of the list by using a negative sign.

Example

 Live Demo

listA = ['Mon','Tue','Wed','Thu','Fri','Sat']
# Given list
print("Given list : \n",listA)
# initializing N
n = 4
# using list slicing
res = listA[-n:]
# print result
print("The last 4 elements of the list are : \n",res)

Output

Running the above code gives us the following result −

Given list :
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
The last 4 elements of the list are :
['Wed', 'Thu', 'Fri', 'Sat']

With isslice

The islice function takes the number of positions as a parameter along with the reversed order of the list.

Example

 Live Demo

from itertools import islice
listA = ['Mon','Tue','Wed','Thu','Fri','Sat']
# Given list
print("Given list : \n",listA)
# initializing N
n = 4
# using reversed
res = list(islice(reversed(listA), 0, n))
res.reverse()
# print result
print("The last 4 elements of the list are : \n",res)

Output

Running the above code gives us the following result −

Given list :
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
The last 4 elements of the list are :
['Wed', 'Thu', 'Fri', 'Sat']

Updated on: 04-Jun-2020

938 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements