
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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']
- Related Articles
- Get positive elements from given list of lists in Python
- Get first and last elements of a list in Python
- Java Program to Get First and Last Elements from an Array List
- Python program to get first and last elements from a tuple
- Get first and last elements from Vector in Java
- Get first and last elements from Java LinkedList
- Python program to find N largest elements from a list
- Program to create a list with n elements from 1 to n in Python
- Python Program to get the last given number of items from the array
- Program to remove last occurrence of a given target from a linked list in Python
- Python How to get the last element of list
- Python program to interchange first and last elements in a list
- How to get first and last elements from ArrayList in Java?
- How to get the last element of a list in Python?
- Python program to remove duplicate elements from a Doubly Linked List\n

Advertisements