Python Tuple index() Method
The index()
method finds the first occurrence of a specified value in a tuple and returns its position (index value).
Syntax
tuple.index(value, start, end)
Parameters
value
(required): The value you want to search in a tuple.
start
(Optional): The index to start the search from (default is 0
).
end
(Optional): The index to end the search at (default is end of tuple).
Return Value
Returns the index (position) of the first occurrence of the value in the tuple. It raises ValueError
if the value is not found in the tuple.
Example 1: Basic Usage
my_tuple = (5, 10, 15, 20, 25, 30)
print(my_tuple.index(15)) # Output: 2
In the above example, value 15
is at index 2
. Therefore, index(15)
returns 2
.
Example 2: Having Multiple Values
When a tuple contains multiple instances of the same value, the index()
method returns the position of the first occurrence only.
my_tuple = (5, 10, 5, 15, 20)
print(my_tuple.index(5)) # Output: 0
In the above code, the value 5
is at index 0
and 2
. Since the index()
method returns the position of the first match only, index(5)
returns 0
.
Example 3: With Start Parameter
my_tuple = ("apple", "banana", "apple", "mango")
print(my_tuple.index("apple", 1)) # Output: 2
In the above example, the value "apple"
appears twice at index 0
and 2
. By passing 1
as the start
parameter to the index()
method, the search starts at index 1
, skipping the first occurrence of "apple"
at index 0
.
As a result, it returns the index of the next occurrence of "apple"
after the starting index, which is 2
.
Example 4: With Start and End Parameters
It is helpful to use the start and end parameters with the index()
method when you are working with a large tuple and want to search within a specific part of a tuple.
my_tuple = ("apple", "banana", "mango", "orange", "pineapple", "apple")
print(my_tuple.index("apple", 1, 4)) # Raises ValueError
In the above example, "apple"
appears at index 0
and 5
. By passing 1
as the start
and 4
as the end
parameter to the index()
method, it searches for "apple"
from index 1
up to (but not including) index 4
. That means the search only looks at "banana"
, "mango"
, and "orange"
. Since "apple"
doesn’t appear in that range, Python raises ValueError
to let you know that the value was not found.
Example 5: Handling Value Not Found
The index()
method raises ValueError
if the value is not found in the tuple. You can easily handle this error using the try-except
block.
For example:
my_tuple = ("apple", "banana", "mango", "orange")
try:
print(my_tuple.index("pineapple"))
except ValueError:
print("Value not found")
Output:
Value not found
Since the value "pineapple"
does not exist in the tuple, a ValueError
is raised, and the except
block runs, printing the message "Value not found"
.