intermediate

Lambda Functions

Learn to create and use anonymous lambda functions.

Lambda functions are small anonymous functions defined with the lambda keyword. They are useful for short, throwaway functions and functional programming patterns.

πŸ“š Concepts & Theory

Lambda functions (also called anonymous functions) are one-line functions defined without the def keyword. They're perfect for short, simple operations.

Basic Lambda Syntax:

lambda parameters: expression

Equivalent Forms:

# Regular function
def add(x, y):
return x + y

# Lambda function
add = lambda x, y: x + y

# Both work the same
print(add(3, 5)) # 8

Key Characteristics:

  • Single expression only (no statements)

  • Implicit return (no return keyword)

  • Can have any number of parameters

  • Often used without naming (inline)
Common Use Cases:

1. Sorting with Custom Key:

students = [
{"name": "Alice", "grade": 85},
{"name": "Bob", "grade": 92},
{"name": "Charlie", "grade": 78}
]

# Sort by grade
sorted_students = sorted(students, key=lambda s: s["grade"])

2. Map Function:

numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x2, numbers))
# [1, 4, 9, 16, 25]

3. Filter Function:

numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4, 6]

4. Reduce Function:**

from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
# 120 (1*2*3*4*5)

Multiple Parameters:

multiply = lambda a, b: a * b
result = multiply(5, 3) # 15

Single Parameter:

square = lambda x: x  2
result = square(4) # 16

No Parameters:

get_greeting = lambda: "Hello, World!"
message = get_greeting()

Lambda with Conditional (Ternary):

is_adult = lambda age: "Adult" if age >= 18 else "Minor"
status = is_adult(20) # "Adult"

When to Use Lambdas:
βœ… Short, simple operations
βœ… One-time use in higher-order functions
βœ… Functional programming patterns
βœ… Callbacks and event handlers

When NOT to Use Lambdas:
❌ Complex logic (use def instead)
❌ Multiple statements needed
❌ Need docstrings or detailed documentation
❌ Code reusability is important

Limitations:

  • Only single expression (no statements like if, while, for)

  • No annotations or docstrings

  • Less readable for complex logic

  • Harder to debug
Best Practice Comparison:
# ❌ Too Complex for Lambda
calculate = lambda x: x
2 if x > 0 else -1 if x < 0 else 0

# βœ… Use def for Complex Logic
def calculate(x):
if x > 0:
return x ** 2
elif x < 0:
return -1
return 0

🎯 Your Challenge

Create a lambda function that takes two numbers and returns their product. Assign it to variable multiply.

πŸ“ Starter Code

Python
# multiply = lambda ...
  • Use lambda keyword to start
  • Parameters come before the colon
  • Expression comes after the colon
  • The expression is automatically returned
  • For multiplication, use x * y

Solution

Python
multiply = lambda x, y: x * y

Explanation

This lambda function demonstrates anonymous function syntax. The lambda keyword declares an anonymous function, x and y are the parameters (separated by commas), the colon separates parameters from the expression, and x * y is the expression that gets evaluated and returned (implicit return). When you call multiply(3, 4), Python evaluates the expression with x=3 and y=4, returning 12. Lambda functions are concise but limited to single expressionsβ€”no statements or multiple lines allowed. They're perfect for simple operations like this multiplication.

⚠️ Common Mistakes to Avoid

  • Forgetting the colon between parameters and expression
  • Trying to use multiple statements (only expressions allowed)
  • Using return keyword (lambdas have implicit return)
  • Forgetting parentheses when calling: multiply vs multiply()
  • Making the lambda too complex (use def for complex logic)

❓ Frequently Asked Questions

Use lambda for simple, one-time operations (especially in map/filter/sorted). Use def for complex logic, reusable functions, or anything needing documentation.
No! Lambdas can only contain a single expression. Use def for multiple statements.
No, lambdas have implicit return. The expression result is automatically returned.
Yes, but only as a ternary expression: lambda x: 'positive' if x > 0 else 'non-positive'

πŸ”— Related Exercises