What you'll learn
- Measure and aggregate with
len,sum,min, andmax - Reorder and pair with
sorted,reversed, andzip - Ask questions of a whole collection with
anyandall - Check a value's type with
isinstanceand find any function's documentation withhelp
Concept
Python ships with about seventy functions that need no import. You have used print, input, len, type, int, float, str, range, and enumerate already. This lesson adds the dozen more that appear in nearly every real file, grouped by what they do. Learn these and you can read most Python you meet.
| Group | Functions | What they do |
|---|---|---|
| Measure | len, sum, min, max |
size and totals of a collection |
| Reorder | sorted, reversed |
a new sorted list; items back to front |
| Combine | zip, enumerate |
walk two lists together; number items |
| Ask | any, all |
is at least one / every item truthy? |
| Inspect | isinstance, type, help, dir |
what is this, and what can it do? |
| Convert | int, float, str, list, round, abs |
change type or shape |
sorted returns a new list and leaves the original alone, which is what you want most of the time. Pass reverse=True for descending order, and pass key= a function to sort by something other than the raw values, like key=len to sort words by length. min and max take the same key argument, which is how the previous lesson found the most common word.
zip walks two or more sequences in step and hands you tuples of matching items, so for name, score in zip(names, scores): pairs them without an index. It stops at the shortest input.

any and all take a collection of truthy or falsy values and collapse them to one answer: any(score > 90 for score in scores) asks whether anyone scored above 90. Swap in all and the same line asks whether every score cleared it.
isinstance(value, int) asks whether a value is an int, and it is the right way to check types because it also accepts subclasses, which will matter when you write classes.
help(sorted) prints the documentation for any function or method, right in the REPL, and dir(value) lists everything a value can do. Those two mean you never have to memorize the string methods table: ask Python.

Code
Measuring and aggregating. sum, min, and max work on any collection of numbers; max with key=len picks the longest word instead of the alphabetically last one.
# measure.py
scores = [72, 95, 58, 88, 61]
words = ["fig", "banana", "kiwi"]
print(len(scores), sum(scores), min(scores), max(scores))
print(f"average {sum(scores) / len(scores):.1f}")
print(max(words))
print(max(words, key=len))
5 374 58 95
average 74.8
kiwi
bananaReordering. sorted never changes its input; key= and reverse= shape the order; reversed walks backwards without sorting.
# reorder.py
scores = [72, 95, 58, 88, 61]
words = ["fig", "banana", "kiwi"]
print(sorted(scores))
print(sorted(scores, reverse=True))
print(scores)
print(sorted(words, key=len))
print(list(reversed(words)))
[58, 61, 72, 88, 95]
[95, 88, 72, 61, 58]
[72, 95, 58, 88, 61]
['fig', 'kiwi', 'banana']
['kiwi', 'banana', 'fig']Pairing with zip and asking with any and all. Both questions read almost like English.
# ask.py
names = ["ada", "grace", "linus"]
scores = [91, 88, 67]
for name, score in zip(names, scores):
print(f"{name}: {score}")
print(any(score > 90 for score in scores))
print(all(score >= 60 for score in scores))
print(all(score >= 70 for score in scores))
ada: 91
grace: 88
linus: 67
True
True
FalseInspecting. isinstance checks a type, and dir shows what a value can do; slicing its result keeps the output short.
# inspect.py
value = "hello"
print(isinstance(value, str), isinstance(value, int))
print(isinstance(3, (int, float)), isinstance(3.5, (int, float)))
print([name for name in dir(value) if not name.startswith("_")][:8])
True False
True True
['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find']Try it yourself
Create report.py with two lists: five product names and five prices. Print the cheapest and most expensive product by name using min and max with zip and a key. Print the products sorted by price, then check with all whether every price is under 100 and with any whether any is under 1. Finally, open the REPL and run help(sorted).
Common mistakes
- Confusing
sorted(x)withx.sort().sortedreturns a new list and works on anything;.sort()changes a list in place and returnsNone. - Passing
key=len()instead ofkey=len. You hand over the function itself, without parentheses; Python calls it for you on each item. - Using
type(x) == intinstead ofisinstance(x, int). It breaks for subclasses, which you will create soon;isinstanceis the habit to build now.
What's next
len,sum,min, andmaxmeasure;sortedreturns a new ordered list, withkey=to choose what to sort by.zippairs sequences by position;anyandallcollapse a collection of conditions to one answer.isinstancechecks types safely, andhelpanddirmean you never need to memorize an API.
You have the built-in toolbox. Next you will start building your own tools: functions, the single most important idea in the whole course.