Tuple Methods
-
This lesson covers important built-in methods available for Python tuples.
Tuple Methods
Unlike lists, tuples have only 2 built-in methods because they are immutable.
1. count() Method
The count() method returns how many times a specified value appears in a tuple.
Syntax
tuple_name.count(value)
numbers = (10, 20, 30, 20, 40, 20)
result = numbers.count(20)
print(result)
Code Explanation
Tuple contains three 20s
count(20) checks frequency
Returns total occurrences
2. index() Method
The index() method returns the position (index) of the first occurrence of a specified value.Syntax
tuple_name.index(value)
numbers = (5, 10, 15, 20, 10)
position = numbers.index(10)
print(position)
Code Explanation
First 10 appears at index 1
Even though 10 appears again, only first position is returned