ItSolutionStuff.com

How to Get Last n Elements of a List in Python?

By Hardik Savani β€’ October 30, 2023
Python

Hey Dev,

In this example, I will show you python get last n elements of list. This tutorial will give you a simple example of how to get last n elements of a list in python. letÒ€ℒs discuss about python list get last n elements. Here you will learn get last n elements of list python.

We can use [-N:] to get the last n elements of the python list. In this example, we will take myList variable with numbers of list. Then we will add n variable to get the last n number of items in the python list. let's see the examples:

You can use these examples with python3 (Python 3) version.

Example:

main.py

# Create New List with Item
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    
n = 4
    
# Get N Number of Item from Last
newList = myList[-n:]
    
print(newList)

Output:

[9, 10, 11, 12]

I hope it can help you...

Tags: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube