Python tuple.index() function


The tuple.index() method in Python is used to find the index of the first occurrence of a specified element within a tuple. If the specified element is not found, it raises a ValueError. This method is useful when you need to locate the position of a particular value in a tuple.

Syntax

tuple.index(value[, start[, end]])
  • value: The element whose index you want to find.
  • start (optional): The starting index from which the search begins. Default is 0.
  • end (optional): The ending index (exclusive) where the search stops. Default is the end of the tuple.

Return Value

  • The method returns the index of the first occurrence of the specified element. If the element is not found, a ValueError is raised.

Example

Here's an example to illustrate how tuple.index() works:

# Example tuple my_tuple = (10, 20, 30, 10, 40) # Finding the index of the first occurrence of 10 index_of_10 = my_tuple.index(10) print(index_of_10) # Output: 0 # Finding the index of 30 index_of_30 = my_tuple.index(30) print(index_of_30) # Output: 2 # Using start and end parameters index_of_10_after_1 = my_tuple.index(10, 1) print(index_of_10_after_1) # Output: 3 # Attempting to find an element that does not exist try: index_of_50 = my_tuple.index(50) except ValueError as e: print(e) # Output: tuple.index(x): x not in tuple

Use Cases

  • Finding Positions: Useful in scenarios where you need to determine the position of elements in data processing or analysis.
  • Validation: Can be used to validate the presence of a particular value within a tuple and retrieve its position.

Summary

The tuple.index() method is a powerful tool for locating the position of elements in a tuple, making it easier to manage and analyze data stored in this immutable data structure.