Python ships with about 70 built-in functions that are always available without an import. A handful of them, used well, replace many lines of loop code: enumerate and zip for looping, sorted, min and max with a key, any and all for checks, and map and filter for transforming data. This lesson shows the ones you will use every day, with the details that often trip people up.
In this lesson you will learn
enumeratefor an index and a value togetherzipfor looping over several sequences, and itsstrictoptionsorted,minandmaxwith akeyfunctionsum,anyandallwith generator expressionsmap,filter,divmod,roundand other helpers
You should know for loops, lists and lambda functions.
Looping Helpers: enumerate, zip, reversed and range
students = ["Nusrat", "Arif", "Tania", "Mitu"]
cgpas = [3.82, 3.41, 3.95, 3.67]
# enumerate: index and value together (start=1 for human numbering)
for rank, name in enumerate(students, start=1):
print(rank, name)
# zip: walk several sequences in parallel
for name, g in zip(students, cgpas):
print(f"{name:<7}{g}")
print(dict(zip(students, cgpas)))
# zip stops at the shortest input; strict=True makes a mismatch an error
print(list(zip([1, 2, 3], "ab")))
try:
list(zip([1, 2, 3], "ab", strict=True))
except ValueError as e:
print("ValueError:", e)
# reversed and range
print(list(reversed(students)), list(range(10, 0, -3)))
Output
1 Nusrat
2 Arif
3 Tania
4 Mitu
Nusrat 3.82
Arif 3.41
Tania 3.95
Mitu 3.67
{'Nusrat': 3.82, 'Arif': 3.41, 'Tania': 3.95, 'Mitu': 3.67}
[(1, 'a'), (2, 'b')]
ValueError: zip() argument 2 is shorter than argument 1
['Mitu', 'Tania', 'Arif', 'Nusrat'] [10, 7, 4, 1]
enumerate(items, start=1)gives pairs of (position, item). It replaces the clumsyfor i in range(len(items))pattern.zippairs up items from several sequences: the first name with the first CGPA, and so on.dict(zip(keys, values))is a quick way to build a dictionary.- By default
zipstops silently at the shortest input, so3was dropped. Addingstrict=True(Python 3.10+) raises an error instead, which catches data that does not line up. reversedwalks a sequence backwards without copying it, andrange(10, 0, -3)counts down in steps of 3.
Sorting, Checking and Transforming
records = [("Nusrat", "CSE", 3.82), ("Arif", "EEE", 3.41), ("Tania", "CSE", 3.95),
("Rafi", "EEE", 2.98), ("Mitu", "CSE", 3.67)]
# sorted, min and max accept a key function
print(sorted(records, key=lambda r: r[2], reverse=True)[0])
print(min(records, key=lambda r: r[2])[0], max(records, key=lambda r: len(r[0]))[0])
print([r[0] for r in sorted(records, key=lambda r: (r[1], -r[2]))])
# sum, any and all with generator expressions
print(round(sum(r[2] for r in records) / len(records), 3))
print(any(r[2] < 3.0 for r in records), all(r[2] > 2.5 for r in records))
# map and filter return lazy iterators
names_upper = map(str.upper, (r[0] for r in records))
print(list(names_upper))
print(list(filter(lambda r: r[1] == "EEE", records)))
# divmod, abs, round, pow with a modulus
print(divmod(125, 60), abs(-7), round(2.675, 2), pow(2, 10, 1000))
print(isinstance(3.5, (int, float)), len("Dhaka"), sorted("banana"))
Output
('Tania', 'CSE', 3.95)
Rafi Nusrat
['Tania', 'Nusrat', 'Mitu', 'Arif', 'Rafi']
3.566
True True
['NUSRAT', 'ARIF', 'TANIA', 'RAFI', 'MITU']
[('Arif', 'EEE', 3.41), ('Rafi', 'EEE', 2.98)]
(2, 5) 7 2.67 24
True 5 ['a', 'a', 'a', 'b', 'n', 'n']
key=tellssorted,minandmaxwhat to compare.key=lambda r: r[2]compares CGPAs, sominfound Rafi and the reversed sort put Tania first.- Returning a tuple from the key sorts by several things:
(r[1], -r[2])means department A–Z, then CGPA high to low. The minus sign reverses one number field. sum,anyandallaccept a generator expression, so no temporary list is built.anystops at the first true value andallat the first false one.mapandfilterreturn lazy iterators; wrap them inlist()to see the values. A list comprehension is often clearer for the same job.divmod(125, 60)gives the quotient and remainder at once (2 hours 5 minutes).pow(2, 10, 1000)computes 210 mod 1000 efficiently.round(2.675, 2)gives 2.67, not 2.68, because 2.675 is stored as a binary number slightly below 2.675. Python also rounds exact halves to the nearest even number, soround(2.5)is 2.
Everyday Built-ins
| Function | Use |
|---|---|
len, sum, min, max | Size, total, smallest, largest |
sorted, reversed | Sorted copy, backward iterator |
enumerate, zip, range | Looping helpers |
any, all | Is any / is every item true? |
map, filter | Transform or select items lazily |
abs, round, divmod, pow | Number helpers |
int, float, str, list, dict, set | Conversions and constructors |
isinstance, type | Check an object’s type |
input, print, open | Input and output |
Common Mistakes
- Using a built-in’s name as a variable, such as
list = [1, 2]orsum = 0. The built-in is then hidden for the rest of that scope. - Using a
maporzipresult twice. They are iterators and are empty after the first pass. Convert to a list if you need it again. - Writing
sorted(data, key=len()). Pass the function itself:key=len. - Calling
list.sort()and expecting a result. It sorts in place and returnsNone;sorted()returns a new list.
Practice Exercises
Exercise 1. Given words = ["mango", "fig", "banana", "kiwi"], find the longest word and sort the words by length, shortest first.
Show answer
print(max(words, key=len)) # banana
print(sorted(words, key=len)) # ['fig', 'kiwi', 'mango', 'banana']
Exercise 2. Two lists hold item prices and quantities. Calculate the total bill in one line.
Show answer
prices = [120, 45, 300]
qty = [2, 4, 1]
print(sum(p * q for p, q in zip(prices, qty, strict=True))) # 720
Frequently Asked Questions
How can I see every built-in function?
Run import builtins; print(dir(builtins)), or read the “Built-in Functions” page of the official Python documentation. help(zip) shows the documentation for one function.
Should I use map and filter or list comprehensions?
Both work. Most Python developers prefer comprehensions such as [x * 2 for x in nums if x > 0] because they read like a sentence. map is neat when you already have a named function, as in map(str.upper, names).
Summary
enumerateandzipmake loops cleaner and safer.key=customisessorted,minandmax; tuples sort by several fields.any,allandsumwork well with generator expressions.- Never reuse built-in names such as
list,sumormaxfor variables.
Next: Python itertools Module.
