Python – Tuple Methods
Do Tuples Have Methods?
Yes, but since tuples are immutable, they only have a few built-in methods compared to lists. These methods do not modify the tuple—they return useful information.
1. count() Method
Purpose:
Returns the number of times a specified value appears in the tuple.
Example:
numbers = (1, 2, 3, 2, 4, 2)
count_2 = numbers.count(2)
print(count_2)Output:
3Explanation:
The value 2 appears 3 times in the tuple.
2. index() Method
Purpose:
Returns the index of the first occurrence of the specified value.
Example:
fruits = ("apple", "banana", "cherry", "banana")
index_banana = fruits.index("banana")
print(index_banana)Output:
1Explanation:
The first "banana" is found at index 1.
Raises ValueError if the Item is Not Found
Example:
colors = ("red", "green", "blue")
print(colors.index("yellow")) # ❌ Not in tupleOutput:
ValueError: tuple.index(x): x not in tupleTips
- Tuples do not have methods like
append(),remove(), orsort()—those are only for lists. - Use
inkeyword to check if a value exists before callingindex()to avoid errors.
Example:
colors = ("red", "green", "blue")
if "yellow" in colors:
print(colors.index("yellow"))
else:
print("Not found")
Extra: Built-in Functions That Work on Tuples
While not tuple methods, these Python built-in functions are commonly used with tuples:
| Function | Description |
|---|---|
len() | Returns the number of items in a tuple |
max() | Returns the largest item |
min() | Returns the smallest item |
sum() | Returns the sum of all items (numeric) |
sorted() | Returns a sorted list from the tuple |
Example:
data = (10, 20, 5, 15)
print(len(data)) # 4
print(max(data)) # 20
print(min(data)) # 5
print(sum(data)) # 50
print(sorted(data)) # [5, 10, 15, 20]Summary
| Method | Description |
|---|---|
count() | Counts how many times a value occurs |
index() | Finds the index of the first occurrence |
| Built-in Function | Works on Tuple? | Returns |
|---|---|---|
len() | ✅ Yes | Number of items |
max() | ✅ Yes | Largest value |
min() | ✅ Yes | Smallest value |
sum() | ✅ Yes | Sum of numeric items |
sorted() | ✅ Yes | Sorted list, not a tuple |