Lambda Syntax
The syntax for a lambda function is:
lambda arguments: expression
# vs a regular function
def function_name(arguments):
return expression
Key rules:
- Can take any number of arguments but only one expression
- The expression is automatically returned β no
returnkeyword - Cannot contain statements (
if/elseblocks, loops, assignments) - Can use conditional expressions (ternary):
x if condition else y
Basic Lambda Examples
# Regular function
def square(x):
return x ** 2
# Equivalent lambda
square = lambda x: x ** 2
print(square(5)) # 25
print(square(10)) # 100
# Multiple arguments
add = lambda a, b: a + b
print(add(3, 7)) # 10
# No arguments
greet = lambda: "Hello, World!"
print(greet()) # Hello, World!
# With conditional expression
absolute = lambda x: x if x >= 0 else -x
print(absolute(-5)) # 5
print(absolute(3)) # 3
Lambda with map()
map(function, iterable) applies a function to every item in an iterable. Lambda is perfect here:
numbers = [1, 2, 3, 4, 5]
# Square every number
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # [1, 4, 9, 16, 25]
# Convert temperatures from Celsius to Fahrenheit
celsius = [0, 20, 37, 100]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
print(fahrenheit) # [32.0, 68.0, 98.6, 212.0]
# Capitalize all strings
names = ["alice", "bob", "charlie"]
capitalized = list(map(lambda s: s.capitalize(), names))
print(capitalized) # ['Alice', 'Bob', 'Charlie']
Lambda with filter()
filter(function, iterable) keeps only items where the function returns True:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]
# Keep numbers greater than 5
greater = list(filter(lambda x: x > 5, numbers))
print(greater) # [6, 7, 8, 9, 10]
# Filter non-empty strings
words = ["hello", "", "world", "", "python"]
non_empty = list(filter(lambda s: s, words))
print(non_empty) # ['hello', 'world', 'python']
# Filter based on length
long_words = list(filter(lambda w: len(w) > 4, words))
print(long_words) # ['hello', 'world', 'python']
Lambda with sorted()
The key parameter in sorted() accepts a function β lambda makes this concise:
# Sort by string length
fruits = ["banana", "apple", "fig", "cherry", "kiwi"]
by_length = sorted(fruits, key=lambda s: len(s))
print(by_length) # ['fig', 'kiwi', 'apple', 'banana', 'cherry']
# Sort in reverse
by_length_desc = sorted(fruits, key=lambda s: len(s), reverse=True)
print(by_length_desc) # ['banana', 'cherry', 'apple', 'kiwi', 'fig']
# Sort list of tuples by second element
points = [(1, 3), (4, 1), (2, 5), (3, 2)]
by_y = sorted(points, key=lambda p: p[1])
print(by_y) # [(4, 1), (3, 2), (1, 3), (2, 5)]
# Sort list of dicts by a key
students = [
{"name": "Alice", "grade": 88},
{"name": "Bob", "grade": 95},
{"name": "Charlie", "grade": 72}
]
by_grade = sorted(students, key=lambda s: s["grade"], reverse=True)
for s in by_grade:
print(f"{s['name']}: {s['grade']}")
Lambda vs def β When to Use Which
| Situation | Use Lambda | Use def |
|---|---|---|
| Simple one-line expression | β | Overkill |
| Passed inline to another function | β | Possible but verbose |
| Multiple lines of logic | β Not possible | β |
| Needs a docstring | β | β |
| Reused multiple times | β (use def for clarity) | β |
| Error handling (try/except) | β | β |
| Key in sorted()/min()/max() | β | Possible |
Avoid assigning a lambda to a variable (f = lambda x: x+1) β that's what def is for. Use lambda anonymously, inline, where a function object is needed temporarily.
Advanced Lambda Patterns
from functools import reduce
# Lambda with reduce() β sum all numbers
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda acc, x: acc + x, numbers)
print(total) # 15
# Lambda returning another lambda (currying)
multiply = lambda x: (lambda y: x * y)
double = multiply(2)
triple = multiply(3)
print(double(5)) # 10
print(triple(5)) # 15
# Lambda in a dictionary (dispatch table)
operations = {
'add': lambda a, b: a + b,
'sub': lambda a, b: a - b,
'mul': lambda a, b: a * b,
'div': lambda a, b: a / b if b != 0 else "Error: division by zero"
}
result = operations['mul'](6, 7)
print(result) # 42
ποΈ Practical Exercise
- Use
map()and lambda to convert a list of prices (floats) to strings with a "$" prefix. - Use
filter()and lambda to extract all negative numbers from a list. - Sort a list of dictionaries representing products by price (lowest first).
- Use
reduce()and lambda to find the product (multiplication) of all elements in a list.
π₯ Challenge Exercise
Build a mini functional data pipeline using only lambdas and higher-order functions. Given a list of raw employee records (dicts with name, salary, department), use lambda + filter to get only Engineering dept, lambda + map to give them a 10% raise, and lambda + sorted to sort by new salary. Print the final list.
Interview Questions
- What is a lambda function in Python? How is it different from a regular function?
- Can a lambda function have multiple lines? Why or why not?
- What are the common use cases for lambda functions?
- What is the difference between map() and filter()? Give examples with lambda.
- What does the sorted() key parameter do? Provide a lambda example.
- When should you prefer def over lambda? What does PEP 8 say about it?
- Can lambda functions access variables from the enclosing scope (closures)?
π Summary
- Lambda creates an anonymous function:
lambda args: expression - The expression is automatically returned β no
returnneeded - Best used inline with
map(),filter(),sorted(), andreduce() - Cannot contain multiple statements, loops, or assignments
- Can use ternary expressions:
lambda x: x if x > 0 else 0 - PEP 8 recommends using
defwhen assigning to a variable name
Related Topics
Frequently Asked Questions
Yes: lambda x, y=10: x + y. The second parameter defaults to 10 if not provided.
Yes: lambda *args: sum(args) and lambda **kwargs: kwargs are both valid. This lets lambdas accept variable arguments.
Generally yes β list comprehensions are slightly faster and more Pythonic for most cases. Use [x**2 for x in nums] over list(map(lambda x: x**2, nums)). Use map+lambda when you already have a named function to pass in.