Skip to the workspace
Pebellslearn by building
Fundamentals  ›  Lesson

Built-in Functions

Builtin Functions 20 minBuilt-in functions are common operations available without importing a module, including len, sum, min and sorted.

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.

Four UPI payments go through filter, which drops the failed ₹99 one, then map, which turns each payment into its amount, then sum, which folds 250, 40 and 500 into 790; a note says filter and map are lazy and run only once

Summarise a cricket innings

A scoring app shows the batting side's runs at a glance:

python

Now the leaderboard wants the top score first. A common first try:

What does this print?
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:

broken — fix itValueError

The 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:

What does this print?
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:

python

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:

python

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.

python

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:

What does this print?
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:

broken — fix itTypeError

A quiet day with no payments crashes the report. Give reduce a start.

One-liners and traps

python

Trap: round(2.5) is 2. Python rounds an exact tie to the nearest even number, and 2.675 is stored as slightly less than it looks, so it becomes 2.67. For money you really charge, use the decimal module.

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

What does this print?
print(sorted("chai"))
What does this print?
print(list(map(int, ["3", "07", "10"])))
What does this print?
print(max([3, 10, 7], key=lambda n: -n))
broken — fix itTypeError

Find 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.

Your task
Build bill_stats(prices). It returns a summary dict with keys total, count, average, highest, lowest. Example: bill_stats([10, 20, 30]) → {"total": 60, "count": 3, "average": 20.0, "highest": 30, "lowest": 10}.

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upAverage

Write average(nums) returning the mean rounded to 2 decimals, or 0 for an empty list.

sumlenguard
DrillTop three

Write top3(nums) returning the three largest values, highest first. Fewer than three? return them all sorted high→low.

sortedslice
BuildSort dishes by price

Each item is [name, price]. Write sort_by_price(items) returning just the names, ordered cheapest → priciest.

sorted-keycomprehension
BossLeaderboard

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.

multi-key-sortenumeratef-strings
CapstoneRecord stats

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.

min/max-keysumguarddict
Project context and further resources
You're building a piece ofBill Splitter & Tip Calculator
This piece — bill_stats(): Summarises the check: total, average, priciest item.
Scenario The manager wants a quick read on the table: total spend, the average plate, and the priciest item.
bill_stats.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
bill_stats(prices) → dictSummary stats for a list of prices.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.