How to Get Last n Elements of a List in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Get First 2, 3, 4, 5, 10, etc Elements from List in Python?
- How to Get Last 2, 3, 4, 5, 10, etc Elements from List in Python?
- Python Remove First 2, 3, 4, 5, 10, etc Elements from List Example
- Python Remove Last 2, 3, 4, 5, 10, etc Elements from List Example
- How to Remove First n Elements from List in Python?
- How to Remove Last n Elements from List in Python?
- Python Create JSON File from List Example
- How to Check If a List is Empty or Not in Python?
- How to Add Element to a List in Python?
- Python List Print All Elements Except First Example
- How to Get Max Value from Python List?
- Python Split String into List of Characters Example