Stop 04 · FunctionsTopics · 6/8

Lambda Functions

Part of the Python Roadmap

In short

Sometimes you need a tiny function for one moment, like "sort these products by price". Writing a full def feels heavy. A lambda is a one-line, nameless function made for exactly those moments.

A lambda is a small, unnamed, one-expression function, such as lambda x: x * 2. It is mostly used as a short key or callback, for example when sorting with sorted(items, key=lambda p: p['price']).

The jaadu slaps a small yellow sticky note onto a messy stack of folders while a thick manual sits unopened on the desk beside it.

Think of it like this

A sticky note instead of a manual

For the office printer you keep a full manual (a def function) with a name, sections and notes. But to tell a colleague "sort these files by date", you scribble it on a sticky note, hand it over, and it's thrown away after. A lambda is that sticky note: one short instruction, used once, often without a name.

Watch it happen

sorted(products, key=lambda p: p["price"])

Kurta 899
0
Saree 2499
1
Dupatta 349
2

1/4Three product dicts. sorted() needs to know what to compare, so we pass a key function.

The big ideas

What you need to know

lambda args: expression

lambda x: x * 2 is a function that takes x and returns x * 2. No return keyword; the expression is the result.

One expression only

No loops, no multiple statements, no assignments. If you need more, write a normal def.

Best as a key or callback

Its main job is sorted(..., key=...), min/max(..., key=...), and arguments to map() and filter().

Named? Use def

PEP 8 advises against double = lambda x: x * 2. If it deserves a name, def double(x): is clearer and shows up better in tracebacks.

See it in code

Walk through the code

python
1double = lambda x: x * 2       # works, but PEP 8 prefers def here2print(double(21))              # 423 4products = [5    {"name": "Kurta", "price": 899},6    {"name": "Saree", "price": 2499},7    {"name": "Dupatta", "price": 349},8]9 10for p in sorted(products, key=lambda p: p["price"]):11    print(p["name"], p["price"])   # Dupatta 349, Kurta 899, Saree 249912 13priciest = max(products, key=lambda p: p["price"])14print(priciest["name"])            # Saree15 16names = ["anil", "Bina", "chirag"]17print(sorted(names))                           # ['Bina', 'anil', 'chirag']18print(sorted(names, key=lambda s: s.lower()))  # ['anil', 'Bina', 'chirag']

1/5A lambda can be stored in a name, but a def is preferred for anything you name.

Lambdas shine as key functions: they tell sorted(), min() and max() what to compare.

Save yourself the pain

Common mistakes

Oops

Cramming complex logic into a lambda with nested conditional expressions.

Do this instead

If you can't read it in one glance, write a named def function instead.

Oops

Calling the key function yourself, as in sorted(products, key=get_price()).

Do this instead

Pass the function itself: key=get_price or key=lambda p: p["price"]. sorted() calls it for you.

Oops

Expecting sorted() to change the original list.

Do this instead

sorted() returns a new list. Use products.sort(key=...) to sort in place.

Your mission

Sort a train timetable

~20 min

Quick check

What does (lambda a, b: a * b)(3, 4) return?

Go deeper

  1. 1Sort a list of (name, marks) tuples by marks using a lambda.
  2. 2Rewrite a lambda as a normal def function to compare readability.
  3. 3Use a named function instead whenever the logic needs more than one simple expression.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge