To get the last n elements of a list using Python, the easiest way is to use slicing.
list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0]
last_5_numbers = list_of_numbers[-5:]
print(last_5_numbers)
#Output:
[0, 3, 0, -1, 0]
You can also use the islice() function from the Python itertools module in combination with the reversed() function.
from itertools import islice
list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0]
last_5_numbers= list(islice(reversed(list_of_numbers), 0, 5))
last_5_numbers.reverse()
print(last_5_numbers)
#Output:
[0, 3, 0, -1, 0]
When working with lists of strings, it can be valuable to be able to easily filter and get only specific values from your list.
One such situation where you may want to get only the last few elements of a list.
In Python, we can easily get the last n elements of a list using slicing.
Slicing allows us to get the last n elements from a list in 1 line.
Below shows how we can use slicing in Python to get the last n elements of a list.
list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0]
last_5_numbers = list_of_numbers[-5:]
print(last_5_numbers)
#Output:
[0, 3, 0, -1, 0]
Using the islice() Function in Python to Get Last N Elements
We can also use the Python islice() function from the Python itertools module to find the last n elements in a list.
First, we need to reverse the list with the Python reversed() function. Then, we use islice, passing 0 and the number of elements we want. Finally, we convert the result back to a list.
Below is an example of how to use the Python islice() function to obtain the last n elements of a list.
from itertools import islice
list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0]
last_5_numbers= list(islice(reversed(list_of_numbers), 0, 5))
last_5_numbers.reverse()
print(last_5_numbers)
#Output:
[0, 3, 0, -1, 0]
I personally think this method isn’t super useful, as the first method with slicing is so easy, but you might find it interesting or valuable.
Hopefully this article has been useful for you to understand how to get the last n elements of a list in Python.