Python | Get last N elements from given list
Accessing elements in a list has many types and variations. These are an essential part of Python programming and one must have the knowledge to perform the same. This article discusses ways to fetch the last N elements of list. Let’s discuss certain solution to perform this task.
Method #1 : Using list slicing
This problem can be performed in 1 line rather than using a loop using the list slicing functionality provided by Python. Minus operator specifies slicing to be done from rear end.
# Python3 code to demonstrate # Get last N elements from list # using list slicing # initializing list test_list = [4, 5, 2, 6, 7, 8, 10] # printing original list print("The original list : " + str(test_list)) # initializing N N = 5 # using list slicing # Get last N elements from list res = test_list[-N:] # print result print("The last N elements of list are : " + str(res)) |
The original list : [4, 5, 2, 6, 7, 8, 10] The last N elements of list are : [2, 6, 7, 8, 10]
Method #2 : Using islice() + reversed()
The inbuilt funtions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end.
# Python3 code to demonstrate # Get last N elements from list # using islice() + reversed() from itertools import islice # initializing list test_list = [4, 5, 2, 6, 7, 8, 10] # printing original list print("The original list : " + str(test_list)) # initializing N N = 5 # using islice() + reversed() # Get last N elements from list res = list(islice(reversed(test_list), 0, N)) res.reverse() # print result print("The last N elements of list are : " + str(res)) |
The original list : [4, 5, 2, 6, 7, 8, 10] The last N elements of list are : [2, 6, 7, 8, 10]
Recommended Posts:
- Python | Merge List with common elements in a List of Lists
- Python | Sorting list of lists with similar list elements
- Python | Replace elements in second list with index of same element in first list
- Python | Add list elements with a multi-list based on index
- Python | Maximum sum of elements of list in a list of lists
- Python | Indices of sorted list of list elements
- Python | Index of Non-Zero elements in Python list
- Python | Get first and last elements of a list
- Python | Check if all elements in a List are same
- Python | List frequency of elements
- Python | Merge list elements
- Python | Absolute value of list elements
- Python | Remove last K elements of list
- Python | Adding two list elements
- Python | Bitwise OR among List elements
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



