Vinay Garg Assistant Professor

Lesson 24: Anonymous functions (lambda) and built-in functions

A lambda is a tiny function written in one line, useful as an argument to another function. Python also ships dozens of built-ins — len, sum, sorted, map, filter, isinstance — that save writing the obvious loop.

A dark code window showing a lambda expression used inside sorted()

In short

  • A lambda is a one-expression function: `lambda n: n * n` is the same idea as a def with one return.
  • Lambdas are for passing a small rule to `sorted()`, `map()` or `filter()`, not for long logic.
  • `map()` transforms every item, `filter()` keeps the items that pass a test, and both return iterators, so wrap them in `list()` to print.
  • Built-ins such as `len`, `sum`, `max`, `sorted`, `abs`, `round` and `isinstance` are always available without an import.

1

expression a lambda may contain

Python docs

0

imports needed for built-in functions

Python docs

What a lambda is

A lambda is an unnamed function written in a single expression. It has no def, no name and no docstring, and it can only contain one expression — no loops, no assignment.

square = lambda n: n * n
print(square(6))        # 36

That line does exactly what a three-line def would do. The point is not brevity for its own sake: a lambda is useful when a function needs a small rule for one call and nowhere else.

The program

# lambda.py — small functions, and the built-ins that use them

square = lambda n: n * n
add = lambda a, b: a + b

print(square(6))          # 36
print(add(3, 4))          # 7

marks = [45, 67, 89, 30]

print(sorted(marks))                          # [30, 45, 67, 89]
print(sorted(marks, reverse=True))            # [89, 67, 45, 30]

names = ["Ravi", "Asha", "Christopher"]
print(sorted(names, key=lambda n: len(n)))    # ['Ravi', 'Asha', 'Christopher']

print(list(map(lambda m: m + 5, marks)))      # [50, 72, 94, 35]
print(list(filter(lambda m: m >= 45, marks))) # [45, 67, 89]

print(len("python"), abs(-9), round(3.6), max(marks), sum(marks))
print(isinstance(5, int), type(3.5).__name__)

How it works, step by step

  1. lambda n: n * n creates a function with one parameter. The part after the colon is the returned expression.
  2. sorted(marks, reverse=True) sorts descending without a lambda, because a number has an obvious order.
  3. Sorting names by length needs a rule, so key=lambda n: len(n) supplies it. key is called once per item.
  4. map() applies the lambda to every item and returns an iterator; list() turns it into something printable.
  5. filter() keeps only the items where the lambda returns True.
  6. The last two lines show ordinary built-ins: they need no import and no definition.

What it prints

36
7
[30, 45, 67, 89]
[89, 67, 45, 30]
['Ravi', 'Asha', 'Christopher']
[50, 72, 94, 35]
[45, 67, 89]
6 9 4 89 231
True float

Built-ins worth knowing

FunctionDoes
len(x)Number of items or characters
sum(x), min(x), max(x)Totals and extremes
sorted(x, key=…, reverse=…)New sorted list
abs(x), round(x, n)Distance from zero, rounding
int(), float(), str()Type conversion
range(a, b, step)Numbers for loops
enumerate(x)Index and value together
zip(a, b)Pairs from two sequences
isinstance(x, type)Type check that respects subclasses
type(x), help(x)Inspect a value, read documentation

Common mistakes

  • Assigning inside a lambda. It cannot hold a statement, so lambda x: y = x is a syntax error.
  • Printing a map() result directly: you get <map object at 0x…>. Wrap it in list().
  • Using a lambda where a named function would be clearer. If the rule needs a comment, it needs a name.

Practice

Try these before moving on. Each one uses only what this lesson covered.

  1. Write a lambda that returns the cube of a number and print the result for 3.
  2. Sort a list of names by their length using `sorted(names, key=...)`.
  3. Use `map()` and `filter()` on a list of marks: add 5 to each, then keep those at least 50.
  4. Rewrite one of your earlier `def` functions as a lambda, and say which style you prefer and why.

Sources

Frequently asked questions

What is a lambda function in Python?

A small unnamed function written in one expression, such as lambda n: n * n. It is used where a function is needed for a moment, usually as the key of sorted() or the argument of map() and filter().

When should I use a lambda instead of def?

When the rule is one short expression used once, such as sorting by the second item of a tuple. For anything longer, or anything used twice, a named def is easier to read and to test.

Why does map() print as an object?

map() and filter() return lazy iterators, not lists. Wrap them in list() to see the values, or loop over them directly.

Are built-in functions faster than my own loops?

Usually, and they are also shorter. sum(), max() and sorted() are implemented in C, so they avoid Python-level loop overhead and are a good default choice.

Vinay Garg

Vinay Garg

Assistant Professor of Computer Science at Multani Mal Modi College, Patiala. Twenty-five years of teaching web programming, and a habit of building the things I teach about.