Built-in functions are common operations available without importing a module, including len, sum, min and sorted.
Choose the operation that matches your question, inspect empty inputs and understand what comparison keys change.
A summary, a ranking and a filter ask different questions about a collection. Python supplies functions for each, but choosing one also chooses behavior for empty inputs, ties and iterator consumption. Use the examples to derive those contracts before replacing your loops.

Summarise a cricket innings
A scoring app shows the batting side's runs at a glance:
Now the leaderboard wants the top score first. A common first try:
scores = [45, 12, 88, 0, 31]
ranked = scores.sort(reverse=True)
print(ranked)Then it rains, and a match is called off before anyone bats:
ValueErrorThe app crashes on a washed-out match. Make it print zeros.
sum([]) is 0 and len([]) is 0, but max([]) and min([]) raise
ValueError. Any time a list might be empty, guard it. Your task below depends
on this.
Preparing this topic’s interactive investigation…
Empty inputs reveal the question you are asking
sum starts with 0 and adds each item. With no items, the starting value
remains. any searches for one truthy item; if there is none, its answer is
false. all searches for a counterexample; with no items, none disproves
“every item passes,” so its answer is true.
These definitions matter for validation. all(price > 0 for price in [])
is true, but it does not establish that an order contains anything. Use
bool(prices) and all(price > 0 for price in prices) if both requirements
matter. any and all stop once the answer is known; do not rely on them
to run a side effect for every item.
max cannot invent a winning item from an empty input. A default is your
policy for that absence, not evidence that zero was observed. An empty
measurement set and an observed measurement of zero should stay distinct
when a report needs to tell them apart.
Pick the cheapest train
A booking app holds fares in a dict and wants the cheapest train:
fares = {"Shatabdi": 1250, "Duronto": 1800, "Rajdhani": 2400}
print(min(fares))Tell min what to compare by. key= takes a function. Python calls it on
every item and compares the results, but still returns the item:
Two things to notice. You pass fares.get, not fares.get(). Functions are
values, and key= wants the function itself so it can call it later. Writing
key=len() calls len right away with nothing, which raises TypeError.
Second, a key that returns a tuple sorts by the first part, then breaks
ties with the next. lambda t: t[1] is a small nameless function, handy when
nothing built-in fits.
To build that dict from two lists, zip pairs them up, position by position:
zip silently drops the extras when the lengths differ. If a train "goes
missing", check your list lengths.
The key is compared; the item is returned
For (name, price) records, key=lambda item: item[1] produces one
comparison value per record. Sorting rearranges the original records; it
does not replace them with prices. Ties keep their original relative order
because Python's sort is stable. min and max return the first
encountered item among equal keys.
A tuple key makes priorities explicit: (price, departure) compares price
first and departure only when prices tie. For numeric scores descending
and names ascending, use (-score, name). Setting reverse=True on
(score, name) reverses both priorities, which is a different policy.
zip pairs by position and normally stops at the shortest input. Where
unequal lengths are an error, zip(names, prices, strict=True) raises
instead (Python 3.10+). Check that contract before turning pairs into a dict;
duplicate names can overwrite earlier rows even when lengths agree.
Total the day's UPI payments
A shop gets payments as (amount, status) pairs. The owner wants today's total
of the successful ones. That is the picture above: filter keeps, map
changes, sum folds.
filter and map hand back iterators, not lists. Print one directly and you
only see <map object at 0x…>. Wrap it in list() to look inside. And an
iterator runs out:
payments = [(250, "ok"), (99, "failed"), (40, "ok"), (500, "ok")]
paid = filter(lambda p: p[1] == "ok", payments)
print(sum(p[0] for p in paid), len(list(paid)))sum only adds. For any other "fold many into one", use reduce from
functools. It carries a running result through the list, two at a time.
It needs a starting value for the day nothing comes in:
TypeErrorA quiet day with no payments crashes the report. Give reduce a start.
One-liners and traps
Trap:
round(2.5)is2. Python rounds an exact tie to the nearest even number, and2.675is stored as slightly less than it looks, so it becomes2.67. For money you really charge, use thedecimalmodule.
Design a ranked delivery list from [name, minutes] records: shortest time
first, names alphabetical on ties. Before coding, write the expected result
for two tied records in reverse alphabetical order. Also choose what the
“fastest delivery” function should return for no records. Reuse a generator
once, then a second time, to demonstrate why a stored iterator and a stored
list have different reuse behavior.
Quick practice
print(sorted("chai"))print(list(map(int, ["3", "07", "10"])))print(max([3, 10, 7], key=lambda n: -n))TypeErrorFind the snack with the longest name.
🎯 Your turn
Write bill_stats(prices). It returns a summary dict with the keys total,
count, average, highest and lowest:
bill_stats([10, 20, 30])→{"total": 60, "count": 3, "average": 20.0, "highest": 30, "lowest": 10}bill_stats([])→{"total": 0, "count": 0, "average": 0.0, "highest": 0, "lowest": 0}
Hint: guard the empty list first (like the rained-off match), then use
sum, len, max, min and round(…, 2) for the average.
Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from an average to a full ranked leaderboard.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write average(nums) returning the mean rounded to 2 decimals, or 0 for an empty list.
Write top3(nums) returning the three largest values, highest first. Fewer than three? return them all sorted high→low.
Each item is [name, price]. Write sort_by_price(items) returning just the names, ordered cheapest → priciest.
Each player is [name, score]. Write leaderboard(players) returning ranked strings "<rank>. <name> — <score>", sorted by score descending, ties broken by name ascending, ranks starting at 1.
Each record is [name, value]. Write stats(records) returning {"count", "total", "average", "highest", "lowest"} where highest/lowest are the whole [name, value] with the max/min value. Empty → count/total/average 0 and highest/lowest None.