Tuple Methods
Because tuples are immutable, they support only two built-in methods:
| Method | Purpose |
|---|---|
count(x) | Number of occurrences of x in the tuple |
index(x) | Index of the first occurrence of x |
t = (1, 2, 3, 2, 4, 2)
print(t.count(2)) # 3
print(t.index(2)) # 1 (first occurrence)
# print(t.index(9)) # ValueError: 9 is not in tuple
Why so few methods?
Methods like append(), remove(), sort(), insert() do not exist for tuples because they would need to modify the tuple in place — which immutability forbids.
t = (5, 3, 1, 4)
# t.sort() # AttributeError: 'tuple' object has no attribute 'sort'
sorted_list = sorted(t) # use the built-in sorted() instead -> returns a list
print(sorted_list) # [1, 3, 4, 5]
Converting between list and tuple when you need mutability
t = (1, 2, 3)
lst = list(t) # convert to list to modify
lst.append(4)
t = tuple(lst) # convert back to tuple
print(t) # (1, 2, 3, 4)
Nested tuple example
students = (("Riya", 92), ("Amit", 78), ("Zoya", 85))
for name, marks in students:
print(name, "scored", marks)