Python List - Slice last N elements
Python List - Slice last N elements
To slice the last N element from a given list in Python, you can use negative indices with slicing. Negative indices count from the end of the list, so you can specify the range of elements you want to extract from the end.
If N is the number of last elements that we need to slice in a list my_list, then the expression is
my_list[-N:]
The above expression returns a new list with the last N elements from the original list.
Examples
In the following examples, we shall go through use cases of slicing last N elements from a given list, when the length of given list is greater than the specified N, and when then the length of given list is less than the specified N.
1. Slice last 3 elements from list in Python
In this example, we are given a list in my_list. We have to slice the last 3 elements from this list using negative indices with list slicing.
Steps
- Given a list in my_list with six elements.
my_list = [10, 20, 30, 40, 50, 60]
- Given N to slice last N elements from the list.
N = 3
- Use list slicing to slice the last N elements of the list my_list using negative index.
my_list[-N:]
This returns a list with the last N elements. Assign it to a variable, say sliced_list.
sliced_list = my_list[-N:]
- You may print the sliced list to output.
print(sliced_list)
Program
The complete program to slice last N elements from a Python list.
Python Program
# Given list
my_list = [10, 20, 30, 40, 50, 60]
# Number of elements to slice from the end
N = 3
# Slice the list
sliced_list = my_list[-N:]
# Print sliced list
print(sliced_list)
Output
[40, 50, 60]
2. Slice last 3 elements from list in Python, but length of list is less than 3
In this example, we are given a list in my_list with only two elements. We have to slice the last 3 elements from this list.
If the length of given list is less than the N (number of last elements to slice), a copy of the original list is returned by the slice expression my_list[-N:].
Python Program
# Given list
my_list = [10, 20]
# Number of elements to slice from the end
N = 3
# Slice the list
sliced_list = my_list[-N:]
# Print sliced list
print(sliced_list)
Output
[10, 20]
Summary
In this Python lists tutorial, we have seen how to slice the last N elements of a given list using negative indices with slicing, provided a step by step explanation, and examples.