Tuple index() Method in Python

Python Tuple index() Method

In Python, the index() method is used to find the index of the first occurrence of a specific element within a tuple. The index refers to the position of the element in the tuple. The method takes the value to search for as an argument and returns the index of the first occurrence of that value. If the value is not found in the tuple, it raises a ValueError.

Here's the syntax of the index() method:

tuple_name.index(value, start, end)
  • tuple_name: This is the name of the tuple on which you want to perform the search.
  • value: This is the element you want to find the index for within the tuple.
  • start (optional): This is the starting index for the search. The search for the element starts from this index. By default, it starts from the beginning of the tuple (index 0).
  • end (optional): This is the ending index for the search. The search for the element is performed up to, but not including, this index. By default, it searches until the end of the tuple.

Here's an example of how to use the index() method:

my_tuple = (10, 20, 30, 40, 50, 30)

# Finding the index of the first occurrence of the value 30
index_of_30 = my_tuple.index(30)
print("Index of 30:", index_of_30)  # Output: Index of 30: 2

# Finding the index of 30 starting from index 3
index_of_30_after_3 = my_tuple.index(30, 3)
print("Index of 30 after index 3:", index_of_30_after_3)  # Output: Index of 30 after index 3: 5

In this example, the index() method is used to find the index of the value 30 in the my_tuple tuple. It first finds the index as 2, which is the position of the first occurrence of 30 in the tuple. Then, using the optional start argument, it finds the index of the second occurrence of 30 after index 3, which is 5.