
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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']
Advertisements