Python Lambda Functions
Table of Contents + −
In the last lesson you learned Variable Length Arguments. There one function could take any number of inputs. Now we look at the other end of the size scale. Sometimes you need a function so tiny that writing a full def for it feels like too much work. That is exactly what a lambda is for.
🤔 Why Lambda Functions?
Say you have a list of names. You want to sort them by length. The sorted() function can do this. But it needs a small helper. The helper tells it “for each name, give me its length”. You could write a full named function for that one job. But it is only one line. You use it once. Then you never touch it again. Writing a whole def for it feels heavy.
A lambda fixes this. It lets you write that tiny helper right where you need it. It fits on a single line. And you do not have to give it a name.
🧩 What Is a Lambda?
A lambda is a small function written on one line that has no name. People also call it an anonymous function. The word “anonymous” just means “no name”.
Think of it like a sticky note. A normal def function is like a page in a notebook. It has a title. It stays around. You can flip back to it any time. A lambda is the sticky note you scribble, use once, and throw away. You would not write a whole notebook page to remember “buy milk”. You grab a sticky note instead. Same idea here.
Here is the shape of a lambda.
lambda parameters: expressionThere are a few parts to read here.
- the word
lambdatells Python “a small function is coming” parametersare the inputs, just like the names inside a normal function’s bracketsexpressionis a single piece of code whose result is returned for you
That last point matters. A lambda has no return keyword. Whatever the expression works out to is what comes back. It happens on its own.
✍️ Lambda vs def: The Same Thing, Two Ways
Let us write the same simple function both ways. Then you can see they really are equal. This is a function that doubles a number.
First the normal way, with def.
def double(x): return x * 2
print(double(5))Output
10Now the exact same thing as a lambda.
double = lambda x: x * 2
print(double(5))Output
10Read the lambda line slowly. lambda x: means “a function that takes one input called x”. Then x * 2 is the expression. Python works it out and hands it straight back. There is no return because a lambda always returns its expression for you.
Both versions do the identical job. The lambda just packs it into one line.
A lambda can take more than one input too. You list the inputs with commas. It is the same way you would in a normal function.
add = lambda a, b: a + b
print(add(3, 4))Output
7Note
Notice we put the lambda into a variable called add here. We did that just to show it works. In real code, giving a lambda a name like this is usually a sign you should have used def instead. The lambda shines when you do NOT name it. You will see that next.
🎯 Where Lambda Really Helps
The best place for a lambda is when a function wants another small function handed to it right then and there. The classic example is the key setting of sorted().
Say Alex has a list of names and wants them sorted from shortest to longest. By default sorted() would sort them alphabetically. To sort by length instead, you give it a key. The key is a small function. It takes one name and returns the value to sort by. Here that value is the length.
names = ["Arjun", "Riya", "Alexander", "Bo"]
by_length = sorted(names, key=lambda name: len(name))
print(by_length)Output
['Bo', 'Riya', 'Arjun', 'Alexander']Walk through what happened.
sorted()goes through each name in the list- for each one it calls our
lambda name: len(name), which hands back the length of that name - it then orders the names by those lengths, smallest first
So Bo (length 2) comes first and Alexander (length 9) comes last. The lambda lived for exactly that one sort and then it was gone. We never needed it again. So we never gave it a name.
Here is a slightly more real example. Imagine a list of people stored as small dictionaries. We want to sort them by age.
people = [ {"name": "Riya", "age": 30}, {"name": "Arjun", "age": 25}, {"name": "Alex", "age": 28},]
youngest_first = sorted(people, key=lambda person: person["age"])
for p in youngest_first: print(p["name"], p["age"])Output
Arjun 25Alex 28Riya 30The lambda takes one person and returns that person’s age. sorted() uses those ages to put everyone in order. Writing a separate named def get_age(person) for this would work too. But the lambda keeps the sorting logic right where you read it.
Lambdas show up the same way as a quick callback. A callback is just a function you hand to another function so it can call it for you. sorted() calling your key is one example. You will see the same pattern with tools like map() and filter(). There you pass a tiny lambda to run on each item.
⚠️ Common Mistakes
A lambda is handy. But it is easy to reach for it in the wrong spot. Watch out for these.
The first one is trying to put a full statement inside a lambda. A lambda holds one expression only. It cannot hold a loop. It cannot hold an if block written as statements. And it cannot hold a print followed by more lines.
# ❌ Avoid: this is not allowed, a lambda can't hold statements like this# square = lambda x:# result = x * x# return result
# ✅ Good: if it needs more than one expression, use defdef square(x): result = x * x return resultThe next one is naming a lambda just to reuse it everywhere. If you assign a lambda to a name and call it in many places, you have basically written a normal function the hard way. Use def so it gets a clear name. Then it can show up properly in error messages.
# ❌ Avoid: a named lambda used like a real functiongreet = lambda name: f"Hi {name}"
# ✅ Good: a real function with a real namedef greet(name): return f"Hi {name}"The last one is cramming too much into one line. Just because you can chain a long expression into a lambda does not mean it reads well. If you have to squint to understand it, it has stopped helping you.
✅ Best Practices
A few simple habits keep lambdas useful instead of confusing.
- Use a lambda for a short, throwaway helper, especially as a
keyor a quick callback. - Keep it to one short, clear expression. If it grows, switch to
def. - Do not assign a lambda to a name. If it deserves a name, it deserves a
def. - Reach for
defwhenever the function is reused, needs a docstring, or needs more than one line. A clear name almost always wins.
Tip
A quick gut check. If you would struggle to read the lambda out loud in one breath, it is too big. Turn it into a normal def.
🧩 What You’ve Learned
✅ A lambda is a tiny, one-line function with no name, also called an anonymous function.
✅ The syntax is lambda inputs: expression, and the expression’s result is returned for you, with no return keyword.
✅ A lambda and a def can do the same job. The lambda just fits on one line.
✅ Lambdas are at their best as a quick helper passed to something else, like the key in sorted() or a callback.
✅ Do not overuse them. For anything longer than one clear expression, a normal def is easier to read.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does the expression `lambda x: x + 1` give you?
Why: A lambda creates a small unnamed function; here it takes x and returns x + 1, with the return happening automatically.
- 2
Which normal function is the same as `lambda a, b: a * b`?
Why: A lambda returns its expression automatically, so `lambda a, b: a * b` matches a def that returns a * b.
- 3
What is the most fitting use of a lambda?
Why: Lambdas shine as small one-line helpers passed to other functions, such as a sorted() key or a quick callback.
- 4
Why can't you put a for loop inside a lambda?
Why: A lambda can only contain one expression; statements such as loops or assignments belong in a normal def.
🚀 What’s Next?
Now you can write tiny functions on the fly. The next step is to understand where the names inside your functions actually live, and who can see them.