Slice a List with Negative Indices in Python
In Python, you can slice a list using negative indices to access elements from the end of the list. The syntax list[start:stop:step]
works with negative indices, where -1
refers to the last element, -2
to the second last, and so on.
Examples
1. Slicing the Last N Elements Using Negative Indices
Using negative indices, we can extract a portion of the list starting from the end.
# Original list
numbers = [10, 20, 30, 40, 50, 60, 70]
# Extracting the last 3 elements
last_three = numbers[-3:]
# Printing the result
print("Last three elements:", last_three)
Explanation
Here, we define a list numbers
containing seven elements. The slicing operation numbers[-3:]
selects elements starting from the third last element (-3) up to the end of the list. Since no stop index is provided, it defaults to the last element.
Output:
Last three elements: [50, 60, 70]
2. Extracting a Middle Section Using Negative Indices
Negative indices can also be used to extract a section of a list from within.
# Original list
letters = ["a", "b", "c", "d", "e", "f", "g"]
# Extracting elements from the third last to the second last
middle_section = letters[-4:-1]
# Printing the result
print("Middle section:", middle_section)
Explanation
We use letters[-4:-1]
to extract a subsection of the list. Here:
-4
corresponds to the fourth last element (“d”).-1
corresponds to the last element, but since slicing excludes the stop index, it stops at “f”.
Output:
Middle section: ['d', 'e', 'f']
3. Reversing a List Using Negative Step
A negative step value allows slicing the list in reverse order.
# Original list
words = ["Python", "Java", "C++", "JavaScript", "Ruby"]
# Reversing the list using slicing
reversed_list = words[::-1]
# Printing the result
print("Reversed list:", reversed_list)
Explanation
The slice words[::-1]
reverses the list by using:
- An empty start and stop index, selecting the whole list.
- A step value of
-1
, which moves from right to left.
Output:
Reversed list: ['Ruby', 'JavaScript', 'C++', 'Java', 'Python']
4. Extracting Every Second Element in Reverse Order
Using a negative step, we can extract elements at regular intervals in reverse.
# Original list
numbers = [10, 20, 30, 40, 50, 60, 70, 80]
# Extracting every second element in reverse
reverse_step = numbers[-1::-2]
# Printing the result
print("Every second element in reverse:", reverse_step)
Explanation
Here, numbers[-1::-2]
does the following:
-1
starts from the last element (80).::-2
selects every second element moving backward.
Output:
Every second element in reverse: [80, 60, 40, 20]
Conclusion
Slicing with negative indices provides an efficient way to work with lists:
- Extracting last elements:
list[-n:]
retrieves the lastn
elements. - Extracting a middle section:
list[-x:-y]
selects a subset. - Reversing a list:
list[::-1]
inverts the order. - Skipping elements in reverse:
list[-1::-step]
selects elements at intervals from the end.