Tuple Methods
A Python tuple is an immutable sequence data type that supports two built-in methods: index() and count(). These methods allow you to query information about the tuple's elements without modifying the tuple itself (since tuples are immutable).
Returns the index of the first occurrence of a specified value in the tuple. If the value is not found, it raises a ValueError.
Syntax: tupleobj.index(value, start=0, end=len(tupleobj)).
# Define a tuple
t1 = (10, 20, 10, 34, 56, 20)
print(t1) # Output: (10, 20, 10, 34, 56, 20)
# Using index()
print(t1.index(20)) # Output: 1 (first occurrence of 20 is at index 1)
print(t1.index(10)) # Output: 0 (first occurrence of 10 is at index 0)
print(t1.index(20, 2)) # Output: 5 (first occurrence of 20 after index 2)
# print(t1.index(99)) # Raises ValueError: 99 is not in tuple
Returns the number of times a specified value appears in the tuple.
Syntax: tupleobj. count(value)
t1 = (10, 20, 10, 34, 56, 20)
print(t1) # Output: (10, 20, 10, 34, 56, 20)
# Using count()
print(t1.count(10)) # Output: 2 (10 appears twice)
print(t1.count(20)) # Output: 2 (20 appears twice)
print(t1.count(99)) # Output: 0 (99 does not appear)2.