11.7 Built-in Functions and Traversal
The general-purpose sequence functions -- len, max, min, sum, sorted, any, all -- work identically on tuples and lists, plus the three idiomatic ways to visit every element: for, while, and enumerate().
Built-in Functions
The same general-purpose sequence functions that work on lists (see 10.8 Built-in Functions) work identically on tuples.
>>> len((3, 1, 4, 1, 5))
5
>>> max((3, 1, 4, 1, 5)), min((3, 1, 4, 1, 5))
(5, 1)
>>> sum((3, 1, 4, 1, 5))
14
>>> any((0, 0, 1)), all((1, 1, 1))
(True, True)
sorted()
Always returns a list, even when given a tuple as input — there’s no in-place tuple.sort(), since tuples can’t be modified.
>>> sorted((3, 1, 4, 1, 5))
[1, 1, 3, 4, 5]
Traversing Tuples
for Loop
>>> for x in (1, 2, 3):
... print(x, end=" ")
1 2 3
while Loop
i = 0
t = (10, 20, 30)
while i < len(t):
print(t[i], end=" ")
i += 1
# Output: 10 20 30
enumerate()
>>> for i, v in enumerate(("a", "b", "c")):
... print(i, v)
0 a
1 b
2 c
Quick Interview Answer
“Every general-purpose sequence function —
len,max,min,sum,any,all— works identically on a tuple as it does on a list, since they only rely on the iterable and comparison protocols, not mutability. The one worth calling out specifically issorted(): it always returns a list, regardless of what type went in, because there’s no such thing as an in-placetuple.sort()— sorting a tuple’s elements necessarily means producing a different object. Traversal is identical to lists too:foris the default,whilefor manual index control,enumerate()for index-value pairs without a counter.”
Common Mistakes
- Expecting
sorted(some_tuple)to return a tuple back — it always returns alist; wrap intuple(sorted(...))if a tuple result is actually needed. - Calling
some_tuple.sort()expecting in-place sorting like a list — tuples have nosort()method at all (see 11.6 Tuple Methods). - Using a
whileloop with manual indexing when a plainforloop accomplishes the same traversal more simply.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form