27-Apr-2023
.
Admin
Hi Dev,
This post will give you an example of getting the last n elements of the List in a Python tutorial example. We will use Python to get the last n elements of the list. you can understand the concept of how to get the last n elements of a list in Python. This article will give you a simple example of a Python list getting the last n elements.
We can use [0:N] to get the last n elements of the Python list. In this example, we will take the myList variable with a number of lists. Then we will add an n variable to get the last n number of items in the Python list. let's see the examples:
Example:
main.py
# Create New List with Item
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
n = 5
# Get N Number of Item from Last
newList = myList[-n:]
print(newList)
Output:
[8, 9, 10, 11, 12]
#Python