Beginner Chapter 47 · 25 min read · Module 4: Python Data Structures
Tuple Methods
- After this chapter you can use count() to find how many times a value appears in a tuple.
- You can use index() to find the position of a value and handle the error when it is missing.
- You can apply len, min, max, sum and sorted to tuples.
- You can join and repeat tuples with + and * and test membership with in.
- You can explain why tuples have so few methods compared with lists.
A tuple is an ordered collection that cannot be changed after it is created. Because of this rule, a tuple does not need methods such as append, remove or sort. Those methods change the object, and a tuple refuses to change. This is why tuples have only two methods of their own: count and index.
This does not mean you can do very little with tuples. Python has many built-in functions and operators that read a tuple and give you a result without changing it. You can measure its length, find the smallest value, add up the numbers, and build a new tuple from old ones.
In this chapter you will learn the two tuple methods, the helpful built-in functions, and the operators that create new tuples. You will also see what to do when you really need a sorted or changed version of a tuple: you build a new one.
Why tuples have only two methods
A list has many methods because a list can grow, shrink and be reordered. A tuple is fixed, so only methods that read information make sense. You can check the full list yourself with dir(tuple); ignoring the names that start with two underscores, you will find just count and index.
The count() method
tuple.count(value) returns how many times the value appears in the tuple. If the value is not present, the answer is 0, and no error is raised. The comparison uses equality, so 1 and 1.0 count as the same value.
marks = (7, 9, 7, 10, 7, 9)
print(marks.count(7))
print(marks.count(9))
print(marks.count(4))The index() method
tuple.index(value) returns the position of the first match. Positions start at 0. If the value is missing, Python raises ValueError. You can pass optional start and stop numbers to search only a part of the tuple, which is useful for finding the second or third match.
days = ("Mon", "Tue", "Wed", "Tue", "Fri")
print(days.index("Tue"))
print(days.index("Tue", 2))
if "Sat" in days:
print(days.index("Sat"))
else:
print("Sat not found")
try:
days.index("Sun")
except ValueError:
print("ValueError caught")in first, or use try/except, before calling index(). A missing value is an error for index() but only a zero for count().Built-in functions that work with tuples
| Function | What it gives | Example result |
|---|---|---|
| len(t) | number of items | len((4, 8, 6)) is 3 |
| min(t) | smallest item | min((4, 8, 6)) is 4 |
| max(t) | largest item | max((4, 8, 6)) is 8 |
| sum(t) | total of numbers | sum((4, 8, 6)) is 18 |
| sorted(t) | new sorted list | sorted((4, 8, 6)) is [4, 6, 8] |
| tuple(x) | tuple from any iterable | tuple('ab') is ('a', 'b') |
Notice that sorted() returns a list, not a tuple. The original tuple is untouched. If you want a tuple again, wrap the result: tuple(sorted(t)). In the same way, reversed() gives an iterator, and t[::-1] gives a reversed tuple using slicing.
temps = (31, 28, 35, 30)
print(len(temps), min(temps), max(temps), sum(temps))
print(sorted(temps))
print(tuple(sorted(temps, reverse=True)))
print(temps[::-1])
print(temps)Operators: joining, repeating and testing
The + operator joins two tuples into a new tuple. The * operator repeats a tuple a number of times. The in and not in operators test whether a value is present. None of them change the original tuples; they create new objects or give a True or False answer.
a = (1, 2)
b = (3,)
c = a + b
print(c)
print(a * 3)
print(2 in c, 5 in c, 5 not in c)
print(a == (1, 2), a < (1, 3))
print(id(a) == id(a + ()))Tuples are compared item by item from the left, like words in a dictionary. That is why (1, 2) < (1, 3) is True. A one-item tuple needs a trailing comma, so write (3,), not (3); the second form is just the number 3 inside brackets.
Changing a tuple the indirect way
You cannot assign to t[0]. If you need a changed version, build a new tuple using slicing and joining, then give it the same name. The old tuple is thrown away when nothing else refers to it. Another fact: a tuple is immutable, but if it holds a list, that list can still change. The tuple keeps pointing to the same list object, while the list contents are free to change.
t = (10, 20, 30)
t = t[:1] + (99,) + t[2:]
print(t)
box = (1, [2, 3])
box[1].append(4)
print(box)
try:
box[0] = 5
except TypeError as e:
print("TypeError")Another useful trick is that count() works well with max() to find the most common item: max(set(t), key=t.count). Be careful, though: when two values tie, the answer may vary between runs because sets have no fixed order, so use it only when you are sure there is one winner.
Python syntax
t.count(value)t.index(value)t.index(value, start, stop)len(t), min(t), max(t), sum(t), sorted(t)new = t1 + t2 / new = t * nReal-world applications
- Counting how many times a grade or a colour appears in fixed data.
- Finding the position of a month or weekday name in a constant tuple.
- Finding the smallest and largest value in a fixed set of readings.
- Building a new record by joining two tuples of data.
Common mistakes
t.append(5) or t.sort() on a tuple.Fix: Tuples have no such methods. Build a new tuple with
+, or use sorted(t) which returns a list.t.index(x) when x may be missing.Fix: Check
x in t first or wrap the call in try/except ValueError.(5) and expecting a tuple.Fix: Add a trailing comma:
(5,).sorted(t) to return a tuple.Fix: It returns a list. Use
tuple(sorted(t)) if you need a tuple.Important tips
- Use
dir(tuple)to see that only count and index exist. - Remember that index() returns only the first match; use start to find later ones.
- Use
t[::-1]for a quick reversed copy.
Key points summary
- Tuples have two methods: count and index.
- count returns 0 for a missing value; index raises ValueError.
- len, min, max, sum and sorted work on tuples and do not change them.
- + and * build new tuples.
- A list inside a tuple can still change.
Exam and interview points
- Tuples are immutable and have only count() and index().
- sorted() on a tuple returns a list.
- (5) is an int, (5,) is a tuple.
- index() raises ValueError when the value is not found.
Quick revision
- count: how many; index: where (first).
- len/min/max/sum/sorted work on tuples.
- + joins, * repeats, in tests.
- Tuple stays fixed; build a new one to change it.
Frequently asked questions
Why does a tuple have no sort method?
sort changes the object in place, and tuples cannot change. Use sorted(t), which returns a new sorted list.
Does count() work with nested tuples?
Yes, but it compares whole items. In ((1, 2), (1, 2), 3), count((1, 2)) is 2, and count(1) is 0.
Can I find all positions of a value?
Use a loop with enumerate, for example [i for i, v in enumerate(t) if v == x], or call index repeatedly with a start value.
Is t + (x,) the same as append?
No. It creates a brand new tuple and leaves the old one unchanged. Repeating it in a big loop is slow.
Practise this chapter
23 practice questions Take the chapter quiz