Python Tuple Methods
Because tuples are immutable, they offer only two built-in methods: count() and index().
Why tuples have so few methods
Lists provide many methods for adding, removing, and reordering items. Tuples cannot be modified after they are created, so all of those mutating methods are absent. What remains are two read-only methods that inspect the contents without changing them: count() and index().
The count() method
count() returns the number of times a given value occurs in the tuple. If the value is not present, it returns 0 rather than raising an error.
Counting occurrences
votes = ("yes", "no", "yes", "yes", "no")
print(votes.count("yes")) # 3
print(votes.count("no")) # 2
print(votes.count("maybe")) # 0The index() method
index() searches the tuple and returns the position of the first item that matches the value you pass in. It stops at the first match, so later duplicates are ignored. If the value does not exist in the tuple, Python raises a ValueError.
Finding a position
letters = ("a", "b", "c", "b", "d")
print(letters.index("c")) # 2
print(letters.index("b")) # 1 (first match only)Combining both methods
These two methods are often used together to summarise data. Here we count how frequently a score appears and locate where it first shows up.
count() and index() together
scores = (7, 9, 7, 3, 9, 9)
print("9 appears", scores.count(9), "times") # 9 appears 3 times
print("first 9 is at index", scores.index(9)) # first 9 is at index 1- count() and index() only read data; they never modify the tuple.
- To change tuple contents, convert it to a list first, edit the list, then convert back with tuple().
- Built-in functions such as len(), min(), max(), and sum() also work on tuples of numbers.