Learn Python
>>> functions.lambda

Lambda Functions in Python

#concept

A lambda is a small, anonymous function written in a single expression, without a name or a def statement. It's most useful for a short piece of logic needed briefly, often passed directly as an argument to another function, rather than being defined and named separately.

#how it works
1

lambda parameters: expression

Defines the function in one line — no def, no name, no return keyword.

2

The expression is returned automatically

There's no explicit return statement needed or allowed.

3

Can be assigned to a variable

Though a regular def is usually clearer for anything that needs a lasting name.

4

Most often passed directly

As the key for sorting, or the function argument to map()/filter().

5

Limited to a single expression

A lambda can't contain multiple statements, loops, or assignments.

#example
square = lambda x: x ** 2
print(square(5))
 
people = [("Ada", 36), ("Grace", 85), ("Alan", 41)]
people.sort(key=lambda person: person[1])
print(people)
Output
25
[('Ada', 36), ('Alan', 41), ('Grace', 85)]
1lambda x: x ** 2 defines a small anonymous function, assigned to the name square, which computes a square.
2people.sort(key=lambda person: person[1]) tells sort to order items by the second element of each tuple (the age) — the lambda is defined right where it’s needed, without a separate name.
3The list ends up sorted by age, from youngest to oldest.
#use cases
A short 'sort by this field' key passed directly into .sort() or sorted()
A quick transformation passed to map(), or a filtering condition passed to filter()
Simple callback functions in GUI or event-driven code that don't need a full named function
Anywhere a tiny, one-off function is needed inline and giving it a name would add more clutter than clarity

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.