Lesson 13 - Lambda Functions
On this page
- Creating Anonymous Functions
- What is a Lambda Function?
- Lambda Functions with Multiple Parameters
- Lambda Functions with No Parameters
- Using Lambda Functions Without Assignment
- Practical Sorting Examples
- Lambda with min() and max()
- When to Use Lambda Functions
- Lambda with Conditional Expressions
- Lambda Limitations
- Practical Examples
- Combining Lambda with List Comprehensions
- Looking Ahead
Creating Anonymous Functions
You’ve already learned how to define functions using the def keyword. But sometimes you need a small, simple function that you’ll only use once. For these cases, Python provides lambda functions—anonymous, single-expression functions that you can define in one line.
Lambda functions are particularly useful in data analytics when working with functions like sorted(), filter(), and map(), which we’ll explore in the next lesson.
By the end of this lesson, you’ll be able to:
- Understand what lambda functions are
- Write lambda functions with correct syntax
- Know when to use lambda vs regular functions
- Apply lambda functions to data processing tasks
- Use lambda with sorting and other built-in functions
Let’s start by understanding what makes lambda functions special.
What is a Lambda Function?
A lambda function is a small anonymous function defined with the lambda keyword instead of def. It can have any number of parameters but only one expression.
Here’s a comparison:
Regular function:
def add_five(x):
return x + 5
result = add_five(10)
print(result)Output:
15Lambda function:
add_five = lambda x: x + 5
result = add_five(10)
print(result)Output:
15Both do exactly the same thing, but the lambda version is more concise.
The basic syntax is:
lambda parameters: expressionlambda: keyword that starts the lambda functionparameters: input variables (can be zero or more):separates parameters from the expressionexpression: a single expression that gets evaluated and returned
Important: Lambda functions can only contain a single expression, not multiple statements or complex logic.
Lambda Functions with Multiple Parameters
Lambda functions can accept multiple parameters:
# Regular function
def multiply(x, y):
return x * y
# Lambda equivalent
multiply = lambda x, y: x * y
print(multiply(4, 5))Output:
20Calculate total price with tax:
total_price = lambda price, tax_rate: price * (1 + tax_rate)
book_price = total_price(12.99, 0.08)
print(f"${book_price:.2f}")Output:
$14.03Three parameters:
calculate_discount = lambda price, quantity, discount: price * quantity * (1 - discount)
total = calculate_discount(9.99, 3, 0.10)
print(f"${total:.2f}")Output:
$26.97Lambda Functions with No Parameters
You can even create lambda functions with no parameters:
get_message = lambda: "Welcome to the bookstore!"
print(get_message())Output:
Welcome to the bookstore!However, this is rarely useful since regular functions are clearer for this purpose.
Using Lambda Functions Without Assignment
The real power of lambda functions comes from using them inline without assigning them to a variable. They’re often used as arguments to other functions.
Using lambda with sorted():
books = [
{"title": "Desert Echoes", "rating": 4.4},
{"title": "Moon Over Pine", "rating": 4.6},
{"title": "Berry Tales", "rating": 4.5}
]
# Sort by rating
sorted_books = sorted(books, key=lambda book: book["rating"])
for book in sorted_books:
print(f"{book['title']}: {book['rating']}")Output:
Desert Echoes: 4.4
Berry Tales: 4.5
Moon Over Pine: 4.6Here’s what’s happening:
sorted()needs to know how to compare the dictionarieskey=lambda book: book["rating"]tells it to use the rating value- The lambda function extracts the rating from each book
sorted()uses these values to order the books
Sort in reverse order:
sorted_books = sorted(books, key=lambda book: book["rating"], reverse=True)
for book in sorted_books:
print(f"{book['title']}: {book['rating']}")Output:
Moon Over Pine: 4.6
Berry Tales: 4.5
Desert Echoes: 4.4Practical Sorting Examples
Sort books by title length:
titles = ["Desert Echoes", "Moon Over Pine", "Berry Tales", "A"]
sorted_titles = sorted(titles, key=lambda title: len(title))
print(sorted_titles)Output:
['A', 'Berry Tales', 'Desert Echoes', 'Moon Over Pine']Sort by price, then by rating:
books = [
{"title": "Desert Echoes", "price": 15.00, "rating": 4.4},
{"title": "Moon Over Pine", "price": 7.50, "rating": 4.6},
{"title": "Berry Tales", "price": 7.50, "rating": 4.5},
{"title": "Golden Harvest", "price": 9.99, "rating": 4.3}
]
# Sort by price, then by rating (descending)
sorted_books = sorted(books, key=lambda book: (book["price"], -book["rating"]))
for book in sorted_books:
print(f"{book['title']}: ${book['price']:.2f} - {book['rating']} stars")Output:
Moon Over Pine: $7.50 - 4.6 stars
Berry Tales: $7.50 - 4.5 stars
Golden Harvest: $9.99 - 4.3 stars
Desert Echoes: $15.00 - 4.4 starsSort by custom criteria:
books = [
{"title": "Desert Echoes", "reviews": 1724500, "rating": 4.4},
{"title": "Moon Over Pine", "reviews": 899000, "rating": 4.6},
{"title": "Berry Tales", "reviews": 985500, "rating": 4.5}
]
# Calculate a popularity score: reviews * rating
sorted_books = sorted(books, key=lambda book: book["reviews"] * book["rating"], reverse=True)
for book in sorted_books:
score = book["reviews"] * book["rating"]
print(f"{book['title']}: {score:,.0f}")Output:
Desert Echoes: 7,587,800
Moon Over Pine: 4,135,400
Berry Tales: 4,434,750Exercise: Create a list of books with price and rating. Sort them by the best “value” (highest rating divided by price). Books priced at $0 should appear last.
Lambda with min() and max()
You can use lambda functions with min() and max() to find items based on custom criteria:
Find the cheapest book:
books = [
{"title": "Desert Echoes", "price": 15.00},
{"title": "Moon Over Pine", "price": 7.50},
{"title": "Berry Tales", "price": 0.00}
]
cheapest = min(books, key=lambda book: book["price"])
print(f"Cheapest: {cheapest['title']} at ${cheapest['price']:.2f}")Output:
Cheapest: Berry Tales at $0.00Find the highest-rated book:
books = [
{"title": "Desert Echoes", "rating": 4.4},
{"title": "Moon Over Pine", "rating": 4.6},
{"title": "Berry Tales", "rating": 4.5}
]
highest_rated = max(books, key=lambda book: book["rating"])
print(f"Highest rated: {highest_rated['title']} - {highest_rated['rating']} stars")Output:
Highest rated: Moon Over Pine - 4.6 starsFind book with most reviews:
books = [
{"title": "Desert Echoes", "reviews": 1724500},
{"title": "Moon Over Pine", "reviews": 899000},
{"title": "Berry Tales", "reviews": 985500}
]
most_reviewed = max(books, key=lambda book: book["reviews"])
print(f"Most reviewed: {most_reviewed['title']} - {most_reviewed['reviews']:,} reviews")Output:
Most reviewed: Desert Echoes - 1,724,500 reviewsWhen to Use Lambda Functions
Use lambda when:
- You need a simple, one-time-use function
- The function is a single expression
- It’s being passed as an argument to another function
- Using it makes the code more concise and readable
Use regular functions when:
- The function contains multiple statements
- The function is complex or needs explanation
- You’ll reuse the function in multiple places
- The function needs documentation
Good use of lambda:
prices = [12.99, 7.50, 15.00, 9.99]
sorted_prices = sorted(prices, key=lambda x: -x) # Sort descendingBad use of lambda (too complex):
# Hard to read!
result = lambda x: x * 2 if x > 10 else x + 5 if x > 5 else x
# Better as a regular function:
def calculate_value(x):
if x > 10:
return x * 2
elif x > 5:
return x + 5
else:
return xLambda with Conditional Expressions
You can use if-else expressions in lambda functions:
# Apply discount to books over $10
apply_discount = lambda price: price * 0.9 if price > 10 else price
prices = [5.99, 12.99, 7.50, 15.00, 9.99]
discounted = [apply_discount(price) for price in prices]
print(discounted)Output:
[5.99, 11.691, 7.5, 13.5, 9.99]Label ratings:
rating_label = lambda rating: "Excellent" if rating >= 4.5 else "Good" if rating >= 4.0 else "Fair"
ratings = [4.7, 4.2, 3.8, 4.6]
labels = [rating_label(r) for r in ratings]
print(labels)Output:
['Excellent', 'Good', 'Fair', 'Excellent']Note: Keep it simple! If the conditional logic gets complex, use a regular function instead.
Lambda Limitations
Lambda functions have important limitations:
1. Only single expressions:
# This won't work - can't have multiple statements
# calculate = lambda x, y: result = x + y; return result
# This works - single expression
calculate = lambda x, y: x + y2. No annotations:
# Regular function with type hints
def add(x: int, y: int) -> int:
return x + y
# Lambda can't have type hints (in older Python versions)
# In Python 3.10+, you can add some annotations but it's not common3. Limited debugging:
# Regular function has a name in error messages
def divide(a, b):
return a / b
# Lambda shows as "<lambda>" in error messages
divide_lambda = lambda a, b: a / b4. No docstrings:
# Regular function can have documentation
def calculate_total(price, quantity):
"""Calculate total price for items.
Args:
price: Price per item
quantity: Number of items
Returns:
Total price
"""
return price * quantity
# Lambda can't have docstringsPractical Examples
Calculate revenue from sales data:
sales = [
{"product": "Desert Echoes", "price": 15.00, "quantity": 50},
{"product": "Moon Over Pine", "price": 7.50, "quantity": 100},
{"product": "Berry Tales", "price": 0.00, "quantity": 200}
]
# Calculate revenue for each product
revenues = list(map(lambda sale: sale["price"] * sale["quantity"], sales))
print(revenues)
# Find the product with highest revenue
top_seller = max(sales, key=lambda sale: sale["price"] * sale["quantity"])
print(f"\nTop seller: {top_seller['product']}")
print(f"Revenue: ${top_seller['price'] * top_seller['quantity']:.2f}")Output:
[750.0, 750.0, 0.0]
Top seller: Desert Echoes
Revenue: $750.00Create a custom comparator:
books = [
{"title": "Desert Echoes", "price": 15.00, "rating": 4.4},
{"title": "Moon Over Pine", "price": 7.50, "rating": 4.6},
{"title": "Berry Tales", "price": 0.00, "rating": 4.5}
]
# Sort free books first, then by rating (descending)
sorted_books = sorted(books, key=lambda b: (b["price"] != 0, -b["rating"]))
for book in sorted_books:
price_str = "Free" if book["price"] == 0 else f"${book['price']:.2f}"
print(f"{book['title']}: {price_str} - {book['rating']} stars")Output:
Berry Tales: Free - 4.5 stars
Moon Over Pine: $7.50 - 4.6 stars
Desert Echoes: $15.00 - 4.4 starsTransform data with calculations:
books = [
{"title": "Desert Echoes", "price": 15.00, "reviews": 1724500, "rating": 4.4},
{"title": "Moon Over Pine", "price": 7.50, "reviews": 899000, "rating": 4.6}
]
# Calculate a quality score
add_score = lambda book: {**book, "score": book["rating"] * (book["reviews"] / 1000000)}
books_with_scores = list(map(add_score, books))
for book in books_with_scores:
print(f"{book['title']}: Score = {book['score']:.2f}")Output:
Desert Echoes: Score = 7.59
Moon Over Pine: Score = 4.14Combining Lambda with List Comprehensions
While you can use lambda in list comprehensions, it’s often clearer to just use the expression directly:
Less clear (using lambda):
prices = [12.99, 7.50, 15.00, 9.99]
doubled = list(map(lambda x: x * 2, prices))More clear (list comprehension):
prices = [12.99, 7.50, 15.00, 9.99]
doubled = [x * 2 for x in prices]However, lambda shines when you need to pass a function as an argument:
# Sorting requires a function argument
sorted_prices = sorted(prices, key=lambda x: -x)Looking Ahead
You’ve now learned how to create and use lambda functions—concise, anonymous functions perfect for simple operations. Lambda functions are particularly powerful when combined with built-in functions like sorted(), min(), and max().
In the next lesson, you’ll learn about filter() and map()—two powerful functions that work beautifully with lambda functions to process and transform data efficiently.
Exercise: Given this list of books:
books = [
{"title": "Desert Echoes", "price": 15.00, "rating": 4.4, "pages": 320},
{"title": "Moon Over Pine", "price": 7.50, "rating": 4.6, "pages": 250},
{"title": "Berry Tales", "price": 0.00, "rating": 4.5, "pages": 180},
{"title": "Golden Harvest", "price": 9.99, "rating": 4.3, "pages": 290}
]Use lambda functions to:
- Sort books by price per page (lowest to highest)
- Find the book with the best rating-to-price ratio (highest rating divided by price, excluding free books)
- Create a list with book titles and a calculated “value score” (rating * pages / max(price, 1))