📘 Lesson 23 · Advanced

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.

basic.py
# 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
▶ Output
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.

sorted.py
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']}")
▶ Output
  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.

map_filter.py
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])
▶ Output
[2, 4, 6, 8, 10, 12]
[2, 4, 6]
[2, 4, 6, 8, 10, 12]
[2, 4, 6]
Use lambda only for simple one-liners — a key function in sorted(), a quick transform in map(). Anything more complex deserves a proper named function.

🧠 Quick Check

What does map(lambda x: x*2, [1,2,3]) return?

[1,2,3]
[2,4,6]
[1,4,9]
[3,6,9]

Tags

lambdaanonymous functionmapfiltersortedfunctional programming