Can negative indexing be used with tuples?

0100

Yes, negative indexing can be used with tuples in Python, just like with strings and lists. It allows you to access elements from the end of the tuple.

Example:

For a tuple my_tuple = (1, 2, 3, 4, 5):

  • my_tuple[0] gives 1 (first element)
  • my_tuple[1] gives 2 (second element)
  • my_tuple[-1] gives 5 (last element)
  • my_tuple[-2] gives 4 (second last element)

Benefits:

  • Convenience: Access the last elements easily without needing to know the tuple's length.
  • Consistency: The same negative indexing rules apply across strings, lists, and tuples.

If you have any more questions or need further clarification, feel free to ask!

0 Comments

no data
Be the first to share your comment!