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`)
Python Tuple Method – Interview Questions
Q 1: Name common tuple methods in Python.
Q 2: What does count() do?
Q 3: What does index() do?
Q 4: Can tuple methods modify the tuple?
Q 5: Can you use len() with a tuple?
Python Tuple Method – Objective Questions (MCQs)
Q1. Which of the following methods returns the count of a specified value in a tuple?
Q2. What will be the output of the following code?
t = (1, 2, 2, 3, 2)
print(t.count(2))
Q3. What does the index() method do in a tuple?
Q4. What will be the output of the following code?
t = ('a', 'b', 'c', 'b')
print(t.index('b'))
Q5. If the value passed to index() does not exist in the tuple, what happens?