How do you access elements of a tuple using negative indexing in Python?
Negative indexing in Python allows you to access elements from the end of a sequence, such as a tuple, by counting backwards from the last element. Here are five examples demonstrating how to access elements of a tuple using negative indexing:
- Accessing the last element of a tuple:
my_tuple = (10, 20, 30, 40, 50)
last_element = my_tuple[-1]
print(last_element) # Output: 50
- Accessing the second-to-last element of a tuple:
my_tuple = (10, 20, 30, 40, 50)
second_last_element = my_tuple[-2]
print(second_last_element) # Output: 40
- Accessing elements from the end of a tuple with a negative step:
my_tuple = (10, 20, 30, 40, 50)
second_to_third_elements = my_tuple[-2:-4:-1]
print(second_to_third_elements) # Output: (40, 30)
- Accessing elements from the end of a tuple using negative indexing within a loop:
my_tuple = (10, 20, 30, 40, 50)
for i in range(-1, -len(my_tuple) - 1, -1):
print(my_tuple[i])
# Output:
# 50
# 40
# 30
# 20
# 10
- Accessing elements with negative indexing when the tuple contains nested tuples:
nested_tuple = ((1, 2), (3, 4), (5, 6))
last_element = nested_tuple[-1][-1]
print(last_element) # Output: 6
These examples demonstrate how you can use negative indexing to access elements of a tuple in Python.