- What are lambda functions — anonymous, one-line functions
- Lambda syntax — how to write lambda functions
- Lambda with map() — transforming data elegantly
- Lambda with filter() — selecting data with conditions
- Lambda with sorted() — custom sorting made easy
- When to use lambda — best practices and use cases
What are Lambda Functions?
A lambda function is a small, anonymous function that can have any number of arguments but can only have one expression. It's a way to create a function without using the def keyword, perfect for simple operations where a full function definition would be overkill.
💡 Key concept: Lambda functions are like a "shortcut" for writing simple functions. They're called "anonymous" because they don't need a name. Think of them as a quick note you write to yourself, rather than a formal document.
Lambda Syntax and Basics
Writing Lambda Functions
# Lambda syntax: lambda arguments: expression
# 1. Basic lambda functions
square = lambda x: x ** 2
print(square(5)) # 25
# 2. Lambda with multiple arguments
add = lambda a, b: a + b
print(add(3, 4)) # 7
# 3. Lambda with conditional expression
is_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(is_even(4)) # Even
print(is_even(7)) # Odd
# 4. Lambda with multiple expressions (not recommended, but possible)
# You can use tuples or list comprehensions
process = lambda x: (x * 2, x ** 2) # Returns a tuple
print(process(5)) # (10, 25)
# 5. Lambda with string operations
greet = lambda name: f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
# 6. Lambda with default arguments
power = lambda x, exp=2: x ** exp
print(power(5)) # 25
print(power(5, 3)) # 125
# 7. Lambda in a list
operations = [
lambda x: x + 1,
lambda x: x * 2,
lambda x: x ** 2,
]
print(operations[0](5)) # 6
print(operations[1](5)) # 10
print(operations[2](5)) # 25
# 8. Lambda as a dictionary value
math_ops = {
'add': lambda a, b: a + b,
'sub': lambda a, b: a - b,
'mul': lambda a, b: a * b,
'div': lambda a, b: a / b,
}
print(math_ops['add'](10, 5)) # 15
print(math_ops['mul'](10, 5)) # 50
Lambda function characteristics:
- Anonymous — no function name needed
- Single expression — can only have one expression
- Returns automatically — the expression result is returned
- Can have multiple arguments — separate with commas
- Can have default values — just like regular functions
Quick Check: What is the syntax for a lambda function? (Answer: lambda arguments: expression)
Lambda with map()
Transforming Data Elegantly
# map() applies a function to every element in an iterable
# Lambda functions are perfect for simple transformations
# 1. Basic map with lambda
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# 2. Map with multiple iterables
a = [1, 2, 3]
b = [10, 20, 30]
sums = list(map(lambda x, y: x + y, a, b))
print(sums) # [11, 22, 33]
# 3. Map with string operations
names = ["alice", "bob", "charlie"]
capitalized = list(map(lambda name: name.capitalize(), names))
print(capitalized) # ['Alice', 'Bob', 'Charlie']
# 4. Map with type conversion
strings = ["1", "2", "3", "4"]
numbers = list(map(int, strings)) # int is a built-in function
print(numbers) # [1, 2, 3, 4]
# 5. Map with multiple operations
numbers = [1, 2, 3, 4, 5]
result = list(map(lambda x: x * 2 + 3, numbers))
print(result) # [5, 7, 9, 11, 13]
# 6. Map with conditional logic
numbers = [1, 2, 3, 4, 5, 6]
result = list(map(lambda x: "even" if x % 2 == 0 else "odd", numbers))
print(result) # ['odd', 'even', 'odd', 'even', 'odd', 'even']
# 7. Map with dictionary values
prices = [10.99, 5.49, 8.75, 12.99]
with_tax = list(map(lambda p: round(p * 1.10, 2), prices))
print(with_tax) # [12.09, 6.04, 9.63, 14.29]
# 8. Map with custom classes
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
products = [
Product("Laptop", 999.99),
Product("Phone", 599.99),
Product("Tablet", 399.99),
]
names = list(map(lambda p: p.name, products))
prices = list(map(lambda p: p.price, products))
print(names) # ['Laptop', 'Phone', 'Tablet']
print(prices) # [999.99, 599.99, 399.99]
map() with lambda key points:
- Transformation — applies a function to every element
- Returns an iterator — use list() to convert to list
- Multiple iterables — can handle multiple sequences
- Perfect for data pipelines — transform data elegantly
Quick Check: What does map() do? (Answer: Applies a function to every element in an iterable)
Lambda with filter()
Selecting Data with Conditions
# filter() keeps elements that satisfy a condition
# Lambda functions are perfect for conditions
# 1. Basic filter with lambda
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]
# 2. Filter with strings
words = ["apple", "banana", "cherry", "date", "elderberry"]
long_words = list(filter(lambda w: len(w) > 5, words))
print(long_words) # ['banana', 'cherry', 'elderberry']
# 3. Filter with multiple conditions
numbers = [10, 15, 20, 25, 30, 35, 40]
result = list(filter(lambda x: x > 20 and x < 35, numbers))
print(result) # [25, 30]
# 4. Filter with predicate functions
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
primes = list(filter(is_prime, numbers)) # Works with regular functions too
print(primes) # [2, 3, 5, 7]
# 5. Filter with dictionaries
data = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 17},
{"name": "Charlie", "age": 30},
{"name": "David", "age": 15},
]
adults = list(filter(lambda p: p["age"] >= 18, data))
print(adults)
# [{'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}]
# 6. Filter with class objects
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
people = [
Person("Alice", 25),
Person("Bob", 17),
Person("Charlie", 30),
Person("David", 15),
]
adults = list(filter(lambda p: p.age >= 18, people))
print([p.name for p in adults]) # ['Alice', 'Charlie']
# 7. Filter with None or empty values
data = ["hello", "", "world", None, "python", "", "programming"]
filtered = list(filter(lambda x: x and x.strip(), data))
print(filtered) # ['hello', 'world', 'python', 'programming']
filter() with lambda key points:
- Selection — keeps elements where condition is True
- Returns an iterator — use list() to convert
- Conditions — any expression that returns boolean
- Data cleaning — perfect for filtering invalid data
Quick Check: What does filter() do? (Answer: Keeps elements that satisfy a condition)
Lambda with sorted()
Custom Sorting Made Easy
# sorted() with key parameter uses lambda for custom sorting
# 1. Sorting by length
words = ["python", "java", "c", "javascript", "go"]
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words) # ['c', 'go', 'java', 'python', 'javascript']
# 2. Sorting by last character
words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=lambda x: x[-1])
print(sorted_words) # ['banana', 'date', 'apple', 'cherry']
# 3. Sorting dictionaries
people = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 20},
]
# Sort by age
by_age = sorted(people, key=lambda p: p["age"])
print(by_age)
# [{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
# Sort by name
by_name = sorted(people, key=lambda p: p["name"])
print(by_name)
# [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}]
# 4. Sorting with custom classes
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"{self.name}({self.age})"
people = [
Person("Alice", 25),
Person("Bob", 30),
Person("Charlie", 20),
]
sorted_people = sorted(people, key=lambda p: p.age)
print(sorted_people) # [Charlie(20), Alice(25), Bob(30)]
# 5. Sorting with multiple keys
data = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 30},
{"name": "David", "age": 20},
]
# Sort by age, then by name
sorted_data = sorted(data, key=lambda p: (p["age"], p["name"]))
print(sorted_data)
# 6. Reverse sorting
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers, key=lambda x: x, reverse=True)
print(sorted_numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
# 7. Sorting with complex calculations
points = [(1, 2), (4, 3), (2, 5), (3, 1)]
# Sort by distance from origin (0, 0)
sorted_points = sorted(points, key=lambda p: p[0]**2 + p[1]**2)
print(sorted_points) # [(1, 2), (3, 1), (2, 5), (4, 3)]
sorted() with lambda key points:
- Custom key — lambda defines what to sort by
- Multiple keys — use tuples for multi-level sorting
- Complex calculations — can compute sort keys
- Reverse sorting — use reverse=True
Quick Check: What is the 'key' parameter in sorted() used for? (Answer: To define custom sorting logic)
Advanced Lambda Patterns
Powerful Lambda Techniques
# 1. Lambda with reduce()
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 120
# 2. Lambda with groupby
from itertools import groupby
data = [{"name": "Alice", "city": "NYC"},
{"name": "Bob", "city": "LA"},
{"name": "Charlie", "city": "NYC"},
{"name": "David", "city": "LA"}]
# Group by city
groups = {}
for city, group in groupby(sorted(data, key=lambda x: x["city"]),
key=lambda x: x["city"]):
groups[city] = list(group)
print(groups)
# {'LA': [{'name': 'Bob', 'city': 'LA'}, {'name': 'David', 'city': 'LA'}],
# 'NYC': [{'name': 'Alice', 'city': 'NYC'}, {'name': 'Charlie', 'city': 'NYC'}]}
# 3. Lambda with min() and max()
numbers = [10, 25, 3, 48, 7, 33]
max_number = max(numbers, key=lambda x: x % 10)
print(max_number) # 48 (48 % 10 = 8, highest remainder)
# 4. Lambda with any() and all()
data = [1, 2, 3, 4, 5]
has_even = any(lambda x: x % 2 == 0, data) # Note: This doesn't work directly
has_even = any(x % 2 == 0 for x in data) # Use generator expression instead
print(has_even) # True
# 5. Lambda with custom functions
def apply_operation(operation, a, b):
return operation(a, b)
result = apply_operation(lambda x, y: x ** y, 2, 5)
print(result) # 32
# 6. Lambda with sorting by attribute
class Product:
def __init__(self, name, price, rating):
self.name = name
self.price = price
self.rating = rating
products = [
Product("Laptop", 999, 4.5),
Product("Phone", 599, 4.8),
Product("Tablet", 399, 4.2),
]
# Sort by rating (descending) then price (ascending)
sorted_products = sorted(products,
key=lambda p: (-p.rating, p.price))
for p in sorted_products:
print(f"{p.name}: ${p.price}, Rating: {p.rating}")
# Phone: $599, Rating: 4.8
# Laptop: $999, Rating: 4.5
# Tablet: $399, Rating: 4.2
# 7. Lambda with conditional expressions
# Using the ternary operator in lambda
get_status = lambda score: "Pass" if score >= 70 else "Fail"
print(get_status(85)) # Pass
print(get_status(65)) # Fail
# 8. Lambda with list comprehension
numbers = [1, 2, 3, 4, 5]
squares = [(lambda x: x ** 2)(x) for x in numbers]
print(squares) # [1, 4, 9, 16, 25]
Advanced lambda techniques:
- reduce() — combine elements with lambda
- groupby() — group data with lambda key
- min()/max() — find extremes with custom key
- Sorting with attributes — sort by multiple criteria
- List comprehension — use lambda inline
Quick Check: What is reduce() used for? (Answer: To reduce an iterable to a single value using a lambda)
Lambda vs Regular Functions
Choosing the Right Tool
# Comparison between lambda and regular functions
# 1. Syntax comparison
# Regular function
def square_regular(x):
return x ** 2
# Lambda function
square_lambda = lambda x: x ** 2
print(square_regular(5)) # 25
print(square_lambda(5)) # 25
# 2. When lambda is better
# ✅ Lambda: Simple, one-line operations
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
# 3. When regular functions are better
# ✅ Regular: Multiple lines, complex logic
def process_data(data):
"""Process data with multiple steps"""
# Multiple lines of logic
cleaned = data.strip().lower()
words = cleaned.split()
filtered = [w for w in words if len(w) > 3]
return filtered
# 4. Lambda limitations
# ❌ Lambda can't have statements (only expressions)
# ❌ Lambda can't have multiple lines
# ❌ Lambda can't have docstrings
# ❌ Lambda can't have annotations
# 5. When to use lambda
# ✅ As a function argument
sorted(people, key=lambda p: p.age)
# ✅ For simple, one-time operations
list(map(lambda x: x * 2, numbers))
# ✅ In functional programming patterns
reduce(lambda x, y: x + y, numbers)
# 6. When NOT to use lambda
# ❌ When you need multiple statements
# ❌ When you need to reuse the function
# ❌ When the logic is complex
# ❌ When you need documentation
# 7. Readability comparison
# Lambda version (less readable for complex logic)
filtered = list(filter(lambda x: x > 5 and x < 20 and x % 2 == 0, numbers))
# Regular function version (more readable)
def is_valid(x):
return x > 5 and x < 20 and x % 2 == 0
filtered = list(filter(is_valid, numbers))
# 8. Best practice guidelines
# Use lambda when:
# - The function is simple (single expression)
# - The function is used only once
# - The function is used as an argument to another function
# Use regular functions when:
# - The function has multiple lines
# - The function is used multiple times
# - The function needs documentation
# - The logic is complex
Lambda vs Regular functions:
- Lambda — simple, one-line, anonymous
- Regular — complex, documented, reusable
- Use lambda — for simple operations, especially as arguments
- Use regular — for complex logic, reusability, clarity
Quick Check: When should you use a lambda function? (Answer: For simple, one-line operations that are used once)
Try It Yourself
Experiment with lambda functions in the editor below. Try creating your own lambdas with map(), filter(), and sorted().
LAMBDA FUNCTIONS PRACTICE
========================================
1. BASIC LAMBDA
Square of 7: 49
10 + 5 = 15
2. LAMBDA WITH MAP()
Squared: [1, 4, 9, 16, 25]
3. LAMBDA WITH FILTER()
Evens: [2, 4, 6, 8, 10]
4. LAMBDA WITH SORTED()
Sorted by length: ['c', 'go', 'java', 'python', 'javascript']
5. LAMBDA WITH DICTIONARIES
Sorted by age: [{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
6. LAMBDA WITH MULTIPLE ARGUMENTS
Sums: [11, 22, 33]
Lambda functions practice complete!
You've Got It!
You now understand lambda functions in Python — when to use them, how they work with map(), filter(), and sorted(), and how to choose between lambda and regular functions.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the difference between lambda and def?
Can a lambda function have multiple lines?
What is the purpose of map() function?
map() applies a function to every element in an iterable and returns an iterator of the results. It's commonly used with lambda functions for simple transformations like squaring numbers or converting data types.
What's a common interview question about lambda functions?
Can I use lambda with multiple conditions?
lambda x: "even" if x % 2 == 0 else "odd". For more complex conditions, consider using a regular function.
Are lambda functions faster than regular functions?
Where to Go From Here
Now that you've mastered lambda functions, check out these related topics:
📝 Assignments
Practice what you've learned with assignments.
Learn More →Iterators
Learn about iterators and how they power functional programming.
Learn More →Generators
Learn about generators for memory-efficient data processing.
Learn More →