Thuta Learning
Python
AdvancedProgrammingBeginner

Built-in Functions (Enhanced)

PythonLesson 5530 min

What you'll walk away with

  • Group built-ins into five jobs: inspect, convert, aggregate, order and iterate
  • Use key= and default= with max(), min() and sorted(), and handle empty input on purpose
  • Explain why map(), filter(), zip() and enumerate() return lazy, one-pass iterators
  • Avoid shadowing built-in names such as list, sum and str with your own variables

Explain it simply

Explain it simply

Built-in functions are the tools that come in the box the moment Python is installed. len() counts, sum() adds, sorted() puts things in order. You use them in any file without writing a single import line.

Most of them are implemented in C, so they are usually faster and less buggy than the for loop you would write by hand. Each tool still has its own small rules, though: what happens with an empty list, whether the result can be used only once, and how the ordering is decided. Knowing those rules is what turns them from handy shortcuts into tools you can trust.

Problem → Why → Solution

The problem: hiding a built-in behind your own name

In a shopping-cart script, the prices are stored in a variable called list and the running total in a variable called sum. Nothing looks wrong at the top of the script.

Forty lines later someone calls list(range(3)) and gets TypeError: 'list' object is not callable. A call to sum() fails with 'int' object is not callable. The line that crashes is far away from the line that caused the damage, which makes this bug slow to track down.

cart.py
list = [4.5, 12.0, 3.25]      # prices
sum = 0
for price in list:
    sum += price

# ... many lines later ...
ids = list(range(3))     # TypeError: 'list' object is not callable
total = sum([1, 2])      # TypeError: 'int' object is not callable

Why does this happen?

Python looks up a name in the order Local, Enclosing, Global, Built-in (LEGB), and built-ins come last. Once a global variable named list exists, Python finds it first and never reaches the real list type. The built-in was not deleted, only hidden; del list makes it visible again.

Core concept: five families of built-ins and their rules

Rather than memorising dozens of built-ins one by one, group them by the job they do. For every family the same three questions apply: what comes back for empty input, is the result a finished list or a lazy iterator, and can a key= argument change how items are compared.

FamilyBuilt-insWatch out for
Inspectlen, type, isinstancePrefer isinstance() over type() == for checks
Convertint, float, str, listint('3.5') raises ValueError
Aggregatesum, min, max, any, allmax([]) raises; sum([]) is 0
Ordersorted, reversedsorted() returns a new, stable list
Iteraterange, enumerate, zip, map, filter, iter, nextLazy, and most are single-pass

1. Decide what empty input means

sum([]) is 0, any([]) is False and all([]) is True. all([]) being True surprises people, but read it as "nobody failed" and it makes sense. max() and min() raise ValueError on empty input unless you pass default=, which they return instead.

2. Change the comparison with key=

key= transforms each item before comparing, yet the original item is what you get back: max(words, key=len) returns the longest word, not its length. sorted() is stable, so items with equal keys keep their original relative order.

3. Remember that lazy results are single-use

map(), filter(), zip(), enumerate() and reversed() hand back iterators, not lists. They produce items only when asked, which saves memory, but once you have looped over one it is exhausted and a second loop yields nothing. Wrap it in list() if you need it twice.

4. Know that zip() stops at the shortest input

If one list in zip(names, ages) is shorter, the extra items are dropped silently. Since Python 3.10, zip(names, ages, strict=True) raises ValueError when lengths differ, so lost data shows up immediately.

Mental model: four questions before you call a built-in
  1. Which family: inspect, convert...?
  2. What happens on empty input?
  3. Finished list or one-pass iterator?
  4. Do I need key= or default=?

If you can answer these four questions, you can predict a built-in's result before running anything.

General pattern

python
size = len(collection)
best = max(items, key=score_of, default=fallback)
ordered = sorted(items, key=score_of, reverse=True)
total = sum(values, start)
ok = all(condition(x) for x in items)
for position, item in enumerate(items, start=1):
    ...
for left, right in zip(first, second, strict=True):
    ...

Aggregating built-ins take optional key= and default= arguments; iterating built-ins are usually unpacked straight inside a for loop.

Example: trying each built-in in turn

This script calls the built-ins family by family and prints each result. Section 5 is new: it shows key=, default= and empty input. str(123) is printed with !r, so the quotes make it visible that the result is a string.

Built-inWhat it does
print()Writes values to the screen (stdout)
len()Returns the number of items in a string, list, dict and so on
type()Returns the data type of a value
max(), min()Return the largest / smallest value
sum()Adds up all the numbers
sorted()Returns a new, sorted list
builtins_tour.py
# ===== 1. Basic Built-in Functions =====
numbers = [10, 20, 5, 40]

print("===== Basic Functions =====")
print(f"Length: {len(numbers)}")       # 4
print(f"Max: {max(numbers)}")           # 40
print(f"Min: {min(numbers)}")          # 5
print(f"Sum: {sum(numbers)}")           # 75
print(f"Sorted: {sorted(numbers)}")     # [5, 10, 20, 40]

# ===== 2. Type Conversion =====
print(f"\n===== Type Conversion =====")
print(f"int('5'): {int('5')}")
print(f"float('3.14'): {float('3.14')}")
print(f"str(123): {str(123)!r}")
print(f"type(123): {type(123)}")

# ===== 3. String Functions =====
print(f"\n===== String Functions =====")
text = "Python"
print(f"len('{text}'): {len(text)}")
print(f"max('{text}'): {max(text)}")
print(f"min('{text}'): {min(text)}")

# ===== 4. Advanced Functions =====
print(f"\n===== Advanced Functions =====")

# map()
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
print(f"map(lambda x: x**2, [1,2,3,4]): {squares}")

# filter()
evens = list(filter(lambda x: x % 2 == 0, nums))
print(f"filter(lambda x: x % 2 == 0, [1,2,3,4]): {evens}")

# zip()
names = ["Sai", "Aye"]
ages = [25, 22]
combined = list(zip(names, ages))
print(f"zip(['Sai','Aye'], [25,22]): {combined}")

# enumerate()
for i, name in enumerate(names):
    print(f"enumerate: {i} = {name}")

# ===== 5. Keys, Defaults and Empty Input =====
print(f"\n===== Keys and Defaults =====")
words = ["kiwi", "fig", "banana"]
print(f"sorted(words, key=len): {sorted(words, key=len)}")
print(f"max(words, key=len): {max(words, key=len)}")
print(f"max([], default=0): {max([], default=0)}")
print(f"sum([]): {sum([])}, any([]): {any([])}, all([]): {all([])}")

Code breakdown

  1. repr of a converted valueprint(f"str(123): {str(123)!r}")

    !r prints the value's repr(), so it shows '123' with quotes and you can see it is a string. Without !r it would print 123, indistinguishable from the int.

  2. max() on a stringprint(f"max('{text}'): {max(text)}")

    A string is a sequence of characters, so max() picks the character with the highest Unicode code point. Lowercase 'y' (121) beats uppercase 'P' (80), which is why max gives y and min gives P.

  3. map() needs list()squares = list(map(lambda x: x**2, nums))

    map() returns a lazy iterator; list() forces every value to be computed into a printable list. Without it you would see <map object ...>.

  4. enumerate() counts for youfor i, name in enumerate(names):

    enumerate() yields (index, item) tuples, so you never maintain a counter with i += 1 yourself. Pass start=1 to count from one.

  5. key= returns the itemprint(f"max(words, key=len): {max(words, key=len)}")

    The comparison uses len, but the result is the word 'banana' itself, not 6. sorted(words, key=len) likewise returns the words, ordered by length.

  6. Empty-input defaultsprint(f"max([], default=0): {max([], default=0)}")

    Without default=0 this line raises ValueError because the iterable is empty. Whenever a report can run on a day with no data, think about the default.

You should see
===== Basic Functions =====
Length: 4
Max: 40
Min: 5
Sum: 75
Sorted: [5, 10, 20, 40]

===== Type Conversion =====
int('5'): 5
float('3.14'): 3.14
str(123): '123'
type(123): <class 'int'>

===== String Functions =====
len('Python'): 6
max('Python'): y
min('Python'): P

===== Advanced Functions =====
map(lambda x: x**2, [1,2,3,4]): [1, 4, 9, 16]
filter(lambda x: x % 2 == 0, [1,2,3,4]): [2, 4]
zip(['Sai','Aye'], [25,22]): [('Sai', 25), ('Aye', 22)]
enumerate: 0 = Sai
enumerate: 1 = Aye

===== Keys and Defaults =====
sorted(words, key=len): ['fig', 'kiwi', 'banana']
max(words, key=len): banana
max([], default=0): 0
sum([]): 0, any([]): False, all([]): True

Hand-written loop or built-in?

Built-ins do more than hide a loop; they name the intent. Someone reading any(x < 0 for x in values) instantly understands "is there a negative?", while a six-line loop with a flag and a break takes a moment to decode. any() and all() also stop as soon as the answer is known (short-circuit), so with a generator expression they do not even compute every item.

Chaining built-ins at all costs can hurt readability, though. In Python a list comprehension is often clearer than list(map(lambda ...)). Use the built-in when the intent is obvious at a glance, and a plain loop when the logic has several branches.

sorted() versus list.sort()

sorted(items) returns a new list, leaves the original alone and accepts any iterable. items.sort() reorders the list in place and returns None, which is why result = items.sort() leaves result set to None.

In real projects

In real projects

One of the most common code-review comments is "this loop can be a built-in". In a sales report, sum() for the total, max(products, key=...) for the best seller and sorted(..., reverse=True) with enumerate(start=1) for the ranking table can remove three loops, and the code starts to read like the report's own description.

What matters is testing the edges. Decide, and test, what the function returns on a day with no sales (an empty list), for two products with the same score (a tie) and for duplicate rows. When there is a tie, max() returns the first item it met; document that if callers depend on it. Linters such as Ruff's builtins rules can flag shadowed built-in names automatically.

Common mistakes

Common mistakes

Using a built-in name as a variable

Naming a variable list, dict, str, sum, max, id or input hides the built-in for that whole scope. Use descriptive names such as prices, total or user_id. If it happens in an interactive shell, del list brings the built-in back.

Looping over an iterator twice

Store pairs = zip(names, ages), print it in one loop, then call dict(pairs), and the dict is empty. No error is raised, which makes it worse. If you need the pairs twice, write pairs = list(zip(names, ages)).

Calling max() on data that can be empty

Code that filters and then calls max() works on test data, then crashes with ValueError on the first day nothing matches the filter. Pass default=None and let the caller handle None.

Mini challenge

Write a score report with built-ins only

Write summarize(), which takes a {name: score} dict and returns a report dict, and print_ranking(), which prints a numbered ranking. Inside summarize() use built-ins and generator expressions only, with no hand-written for loop.

  • Return the keys count, top (best scorer), average (one decimal place), all_passed, any_perfect and ranking
  • An empty dict must not crash: top and average become None
  • print_ranking() numbers the rows from 1 using enumerate(start=1)
score_report.py
def summarize(scores: dict[str, int], pass_mark: int = 50) -> dict:
    """Describe a score table using built-ins only (no explicit loops)."""
    # TODO: count       -> how many students
    # TODO: top         -> name with the highest score (None when empty)
    # TODO: average     -> rounded to 1 decimal (None when empty)
    # TODO: all_passed  -> every score >= pass_mark
    # TODO: any_perfect -> at least one score of 100
    # TODO: ranking     -> names, best first
    return {}


def print_ranking(scores: dict[str, int]) -> None:
    # TODO: sort (name, score) pairs by score, best first
    # TODO: print "  1. Name score" lines, numbered from 1
    pass


class_a = {"Aye": 82, "Sai": 47, "Mya": 91, "Hla": 66}
print(summarize(class_a))
print_ranking(class_a)
print(summarize({}))

Expected: For class_a: top is 'Mya', average is 71.5, all_passed is False, followed by four ranking lines. For the empty dict: top and average are None and all_passed is True.

Show hint

max(scores, key=scores.get, default=None) compares the dict's keys by their values. For the average, guard against an empty dict with ... if scores else None.

Show solution
score_report.py
def summarize(scores: dict[str, int], pass_mark: int = 50) -> dict:
    """Describe a score table using built-ins only (no explicit loops)."""
    values = scores.values()
    return {
        "count": len(scores),
        "top": max(scores, key=scores.get, default=None),
        "average": round(sum(values) / len(scores), 1) if scores else None,
        "all_passed": all(v >= pass_mark for v in values),
        "any_perfect": any(v == 100 for v in values),
        "ranking": sorted(scores, key=scores.get, reverse=True),
    }


def print_ranking(scores: dict[str, int]) -> None:
    ranking = sorted(scores.items(), key=lambda item: item[1], reverse=True)
    for place, (name, score) in enumerate(ranking, start=1):
        print(f"  {place}. {name:<4} {score}")


class_a = {"Aye": 82, "Sai": 47, "Mya": 91, "Hla": 66}
print(summarize(class_a))
print_ranking(class_a)
print(summarize({}))

Quick quiz 1 / 3

Given words = ["kiwi", "fig", "banana"], what does max(words, key=len) return?

Quick quiz 2 / 3

After pairs = zip(["a", "b"], [1, 2]), you run print(list(pairs)) and then print(dict(pairs)). What does the second line print?

Quick quiz 3 / 3

In a report function the scores list may be empty. How should you get the highest score?

What to remember

  • Group built-ins by job: inspect, convert, aggregate, order and iterate
  • sum([]) is 0, all([]) is True, max([]) raises ValueError unless you pass default=
  • key= changes how items are compared, but the original item is what you get back
  • map, filter, zip and enumerate are single-use iterators, and names like list, sum and str must never be shadowed

The Python Tutorial — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Built-in Functions (Enhanced) | Thuta Learning