Explain negative indexing?

0117

Negative indexing in Python allows you to access elements of a sequence (like a string, list, or tuple) from the end rather than the beginning. Here's how it works:

  • Indexing Starts from 0: In positive indexing, the first element is at index 0, the second at index 1, and so on.
  • Negative Indices Count Backwards: Negative indices start from -1 for the last element, -2 for the second last, and so forth.

Example:

For the string s = "Hello":

  • s[0] gives 'H' (first character)
  • s[1] gives 'e' (second character)
  • s[-1] gives 'o' (last character)
  • s[-2] gives 'l' (second last character)

Benefits:

  • Convenience: It allows easy access to elements at the end of a sequence without needing to know its length.
  • Flexibility: You can easily retrieve elements regardless of the sequence's size.

Feel free to ask if you need more examples or clarification!

0 Comments

no data
Be the first to share your comment!