In Python, tuples have only two built-in methods since they are immutable and limited in functionality compared to lists. Here are the two tuple methods:
count()
The count()
method returns the number of times a specified value appears in a tuple.
Syntax:
tuple.count(value)
Example:
my_tuple = (1, 2, 3, 4, 5, 5, 6, 7, 8, 5)
count_of_5 = my_tuple.count(5)
print(count_of_5) # Output: 3 (because `5` appears three times)
index()
The index()
method returns the index of the first occurrence of a specified value in the tuple.
If the value is not present, it raises a ValueError
.
Syntax:
tuple.index(value)
Example:
my_tuple = (10, 20, 30, 20, 40)
index_of_20 = my_tuple.index(20)
print(index_of_20) # Output: 1 (index of the first occurrence of `20`)