How to Use Lambda in Python
What you’ll build or solve
You’ll write and use lambda functions for quick, single-expression logic.
When this approach works best
A lambda works well when you:
Learn Python on Mimo
- Pass a short function to
sorted(), like sorting by the second item in a tuple. - Transform values in a pipeline, like converting a list of strings to integers.
- Filter data with a simple rule, like keeping only items longer than 3 characters.
Avoid lambdas when the logic needs multiple steps, branching, or reuse. Use def so you can name the function, add comments, and test it independently.
Prerequisites
- Python installed
- You know what a function is
Step-by-step instructions
1) Write a lambda function
A lambda is an anonymous function with this shape:
add=lambdaa,b:a+b
print(add(2,3))
What to look for:
A lambda can only contain one expression. You cannot put statements like try/except or multi-line logic inside it.
2) Use a lambda as a key function for sorting
This is one of the most common uses. The lambda returns the value Python should sort by.
people= [
{"name":"Naomi","age":30},
{"name":"Ivan","age":22},
{"name":"Lea","age":27},
]
sorted_people=sorted(people,key=lambdaperson:person["age"])
print(sorted_people)
Option A: Sort by two fields
people= [
{"name":"Naomi","age":30},
{"name":"Ivan","age":22},
{"name":"Lea","age":22},
]
sorted_people=sorted(
people,
key=lambdaperson: (person["age"],person["name"])
)
print(sorted_people)
What to look for:
Return a tuple for multi-field sorting. Python compares the first element, then the next if there is a tie.
3) Use a lambda with map() and filter()
Use map() to transform items, and filter() to keep items that match a condition.
numbers= ["1","2","3","10"]
as_ints=list(map(lambdas:int(s),numbers))
print(as_ints)
Option A: Filter items
words= ["hi","hello","podgorica","ok"]
long_words=list(filter(lambdaw:len(w)>3,words))
print(long_words)
What to look for:
map() and filter() return iterators in Python 3. Wrap them in list() if you want to print the results or reuse them.
Examples you can copy
Example 1: Sort a list of tuples by the second value
pairs= [("a",3), ("b",1), ("c",2)]
sorted_pairs=sorted(pairs,key=lambdaitem:item[1])
print(sorted_pairs)
Example 2: Sort strings case-insensitively
names= ["Mila","ana","Ivan"]
sorted_names=sorted(names,key=lambdas:s.casefold())
print(sorted_names)
Example 3: Convert a list of prices like "€10" into integers
prices= ["€10","€2","€7"]
numbers=list(map(lambdap:int(p.lstrip("€")),prices))
print(numbers)
Example 4: Filter out empty or whitespace-only strings
CSS
items= ["ok"," ","","done"," "]
clean=list(filter(lambdas:s.strip()!="",items))
print(clean)
Example 5: Build a quick lookup mapping from data
users= [
{"id":"u1","name":"Naomi"},
{"id":"u2","name":"Ivan"},
]
id_to_name=dict(map(lambdau: (u["id"],u["name"]),users))
print(id_to_name)
Common mistakes and how to fix them
Mistake 1: Putting complex logic into a lambda
What you might do
numbers= [1,2,3,4]
result=list(
map(lambdan:n*2ifn%2==0elsen*3ifn>2elsen,numbers)
)
print(result)
Why it breaks
This works, but it is hard to read and easy to mess up.
Fix
Use a named function:
deftransform(n):
ifn%2==0:
returnn*2
ifn>2:
returnn*3
returnn
numbers= [1,2,3,4]
result=list(map(transform,numbers))
print(result)
Mistake 2: Forgetting that map() and filter() return iterators
What you might do
numbers= ["1","2","3"]
mapped=map(lambdas:int(s),numbers)
print(mapped)
Why it breaks
Printing shows an iterator object, not the values.
Fix
Convert to a list (or loop over it):
numbers= ["1","2","3"]
mapped=list(map(lambdas:int(s),numbers))
print(mapped)
Troubleshooting
If you get a syntax error in a lambda, check that you used only one expression and no statements.
If sorting results look wrong, print the key you return from the lambda for a couple of items to confirm it matches what you want.
If map() or filter() seems empty on the second use, you already consumed the iterator. Convert to a list if you need to reuse it.
If a lambda feels unreadable, switch to def and give it a clear name.
If your lambda accesses a missing dictionary key, use get() or validate the data before sorting or mapping.
Quick recap
- Use
lambda args: expressionfor short, one-off functions. - Lambdas work best as
key=functions forsorted()and quick transforms withmap()orfilter(). - Lambdas can only contain one expression.
- Convert
map()andfilter()to a list when you need to print or reuse the results. - Use
defwhen the logic is more than a simple expression.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot