Negative indexing in Python allows you to access elements from the end of a sequence, such as a list or a string. Here's how it works:
- Indexing Starts from Zero: In a sequence, the first element is at index
0, the second at index1, and so on. - Negative Indices: When you use a negative index, Python counts from the end of the sequence:
-1refers to the last element.-2refers to the second-to-last element.-3refers to the third-to-last element, and so forth.
Example:
my_list = [10, 20, 30, 40, 50]
print(my_list[-1]) # Output: 50 (last element)
print(my_list[-2]) # Output: 40 (second-to-last element)
This feature is particularly useful when you want to access elements without needing to calculate their positive index. If you have more questions or need further clarification, feel free to ask!
