Python Lambda Functions
Learn anonymous lambda functions with map(), filter(), sorted() and practical examples.
What is a Lambda?
A lambda is a small anonymous function written in one expression:
lambda parameters: expression. No name, no def, no return
keyword needed. Lambdas are best used for short throwaway functions — especially as arguments to
higher-order functions like sorted(), map(), and filter().
For anything more complex, write a proper named function instead.
# Named function def square(x): return x ** 2 # Lambda — same behaviour, no name sq = lambda x: x ** 2 print(square(5)) print(sq(5)) print((lambda x, y: x + y)(3, 4)) # called immediately
25 25 7
Lambda with sorted()
The most practical use of lambda is as the key argument in sorted().
The key function extracts the sorting value from each item. This lets you sort complex objects by
any attribute without writing a full named function.
people = [ {{"name": "Charlie", "age": 30}}, {{"name": "Alice", "age": 25}}, {{"name": "Bob", "age": 35}}, ] by_age = sorted(people, key=lambda p: p["age"]) for p in by_age: print(f" {p['name']}: {p['age']}")
Alice: 25 Charlie: 30 Bob: 35
map() and filter()
map(func, iterable) applies a function to every item. filter(func, iterable)
keeps only items where the function returns True. Both return lazy iterators — wrap in list()
to see the results. Note that list comprehensions are often more readable for the same task.
nums = [1, 2, 3, 4, 5, 6] doubled = list(map(lambda x: x*2, nums)) print(doubled) evens = list(filter(lambda x: x%2==0, nums)) print(evens) # List comprehensions — same result, often clearer print([x*2 for x in nums]) print([x for x in nums if x%2==0])
[2, 4, 6, 8, 10, 12] [2, 4, 6] [2, 4, 6, 8, 10, 12] [2, 4, 6]
🧠 Quick Check
What does map(lambda x: x*2, [1,2,3]) return?