Access Elements in a Python List Using Negative Index
In Python, lists support negative indexing, allowing you to access elements from the end of the list.
Understanding Negative Indexing in Python
In Python, list indices start from 0
for the first element. However, using negative indexing, we can access elements from the end of the list:
-1
refers to the last element.-2
refers to the second-last element.-3
refers to the third-last element, and so on.
1. Accessing Elements Using Negative Indexing
In this example, we access the last and second-last elements of a list using negative indexing.
# Define a list of fruits
fruits = ["apple", "banana", "cherry", "date"]
# Access the last element (index -1)
last_fruit = fruits[-1]
# Access the second-last element (index -2)
second_last_fruit = fruits[-2]
# Print results
print("Last fruit:", last_fruit)
print("Second last fruit:", second_last_fruit)
Output:
Last fruit: date
Second last fruit: cherry
Here:
fruits[-1]
retrieves"date"
, the last element.fruits[-2]
retrieves"cherry"
, the second-last element.
2. Extracting a Sublist Using Negative Index Slicing
Negative indices can also be used with slicing to extract portions of a list.
Here, we extract the last three elements from the list using negative indices.
# Define a list of fruits
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
# Extract the last three elements
sublist = fruits[-3:]
# Print the sublist
print("Sliced list:", sublist)
Output:
Sliced list: ['cherry', 'date', 'elderberry']
fruits[-3:]
extracts elements starting from the third-last element ("cherry"
) to the end.
3. Reversing a List Using Negative Indexing
Negative indexing can be combined with slicing to reverse a list.
We use slicing with a step of -1
to reverse the list.
# Define a list of fruits
fruits = ["apple", "banana", "cherry", "date"]
# Reverse the list using slicing
reversed_fruits = fruits[::-1]
# Print the reversed list
print("Reversed list:", reversed_fruits)
Output:
Reversed list: ['date', 'cherry', 'banana', 'apple']
fruits[::-1]
tells Python to step backwards through the list, effectively reversing it.
Conclusion
Negative indexing provides a convenient way to access elements from the end of a list in Python.
-1
refers to the last element,-2
refers to the second-last, and so on.- Negative indices can be used with slicing to extract sublists.
- Reversing a list can be done using
[::-1]
.