How does negative indexing work?

0119

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 index 1, and so on.
  • Negative Indices: When you use a negative index, Python counts from the end of the sequence:
    • -1 refers to the last element.
    • -2 refers to the second-to-last element.
    • -3 refers 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!

0 Comments

no data
Be the first to share your comment!