Part 10 / Topic 3 of 11
Useful built-ins
These built-in functions replace many hand-written loops. Think of them as the power tools in a toolbox: one tool, one clear job.
| Built-in | What it does | Example result |
|---|---|---|
enumerate(items, start=1) |
gives (number, item) pairs |
(1, 'Idli') |
zip(a, b) |
pairs items from two lists | ('Asha', 91) |
any(checks) |
True if at least one is true |
|
all(checks) |
True if every one is true |
|
sorted(items, key=f) |
new sorted list, sorted by f(item) |
|
min/max(items, key=f) |
smallest/biggest by f(item) |
Real-world example: a class results board.
names = ["Asha", "Ravi", "Meera"]
marks = [91, 78, 85]
for rank, (name, mark) in enumerate(zip(names, marks), start=1):
print(rank, name, mark)
print(dict(zip(names, marks))) # {'Asha': 91, 'Ravi': 78, 'Meera': 85}
print(any(m < 80 for m in marks)) # True (someone scored below 80)
print(all(m >= 35 for m in marks)) # True (everyone passed)
pairs = list(zip(names, marks))
print(sorted(pairs, key=lambda p: p[1], reverse=True))
# [('Asha', 91), ('Meera', 85), ('Ravi', 78)]
print(min(pairs, key=lambda p: p[1])) # ('Ravi', 78)
The loop prints:
1 Asha 91
2 Ravi 78
3 Meera 85
Sort by two things with a tuple key. Use - to reverse a number inside the key:
staff = [("Pune", 30000), ("Delhi", 45000), ("Pune", 52000)]
print(sorted(staff, key=lambda s: (s[0], -s[1])))
# [('Delhi', 45000), ('Pune', 52000), ('Pune', 30000)]
Unpacking with * and **
* takes "the rest" of a sequence; ** spreads a dict. You used them in function calls in Part 5; they also work in assignments and literals.
first, *rest = [101, 102, 103, 104]
print(first, rest) # 101 [102, 103, 104]
*_, last = [101, 102, 103, 104] # _ means "I do not need these"
print(last) # 104
morning = ["Asha", "Ravi"]
evening = ["Meera"]
print([*morning, *evening]) # ['Asha', 'Ravi', 'Meera']
defaults = {"currency": "INR", "gst": 18}
custom = {"gst": 12}
print({**defaults, **custom}) # {'currency': 'INR', 'gst': 12} (later wins)
๐ Going deeper:
zipstops at the shortest list. Usezip(a, b, strict=True)to get aValueErrorif the lengths differ.any/allstop early as soon as the answer is known.
Full program: examples/01_pythonic_rewrite.py.
Done here? The practice set for Part 10 โ 8 exercises with solutions โ is on the part page.