Fundamentals · Lesson 15 of 94

Built-in functions you'll use every day

Watch this lesson

View full playlist ↗

Read the lesson

What you'll learn

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.

Built-in functions you'll use every day: names: ada, grace → scores: 91, 88 → ('ada', 91) → ('grace', 88)
Built-in functions you'll use every day · Figure 1 · Open for full size

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.

Built-in functions you'll use every day: What can this value do? → dir(value) → a list of method names → help(value.method) → the explanation
Built-in functions you'll use every day · Figure 2 · Open for full size

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))
Output
5 374 58 95
average 74.8
kiwi
banana

Reordering. 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)))
Output
[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))
Output
ada: 91
grace: 88
linus: 67
True
True
False

Inspecting. 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])
Output
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

What's next

You have the built-in toolbox. Next you will start building your own tools: functions, the single most important idea in the whole course.

Course overview