Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
Why Functions?Parameters & ArgumentsReturn StatementsScopeDefault ParametersVariable Arguments (*args)Lambda FunctionsDecoratorsFunctional ProgrammingBest Practices
Python/Functions/Lambda Functions

🔥 Lambda Functions — Anonymous Functions

Lambda functions are one-line, unnamed functions perfect for simple operations.


🎯 What is a Lambda Function?

A lambda function is a small anonymous function defined with the `lambda` keyword:

# Regular function
def square(x):
    return x ** 2

# Equivalent lambda function
square = lambda x: x ** 2

print(square(5))  # 25

📝 Lambda Syntax

lambda parameters: expression

Components:

  • `lambda` — Keyword
  • `parameters` — Input variables (comma-separated)
  • `:` — Separator
  • `expression` — Single expression to evaluate and return

💡 Common Lambda Use Cases

Single Parameter

# Regular function
def add_ten(x):
    return x + 10

# Lambda equivalent
add_ten = lambda x: x + 10

print(add_ten(5))   # 15
print(add_ten(20))  # 30

Multiple Parameters

# Regular function
def add(a, b):
    return a + b

# Lambda equivalent
add = lambda a, b: a + b

print(add(5, 3))    # 8
print(add(10, 20))  # 30

Conditional Lambda

# Check if even
is_even = lambda x: x % 2 == 0

print(is_even(4))   # True
print(is_even(7))   # False

# Return different values
grade = lambda score: "A" if score >= 90 else "B" if score >= 80 else "C"

print(grade(95))    # A
print(grade(85))    # B
print(grade(75))    # C

🎨 Lambda with map()

Transform each element in a list:

numbers = [1, 2, 3, 4, 5]

# Square each number
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

# Convert to strings
strings = list(map(lambda x: str(x), numbers))
print(strings)  # ['1', '2', '3', '4', '5']

# Double each number
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)  # [2, 4, 6, 8, 10]

🔍 Lambda with filter()

Keep only elements that match a condition:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Filter even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6, 8, 10]

# Filter numbers > 5
greater_than_five = list(filter(lambda x: x > 5, numbers))
print(greater_than_five)  # [6, 7, 8, 9, 10]

# Filter non-empty strings
words = ["hello", "", "world", "", "python"]
non_empty = list(filter(lambda w: w != "", words))
print(non_empty)  # ['hello', 'world', 'python']

➕ Lambda with reduce()

Combine all elements into a single result:

from functools import reduce

numbers = [1, 2, 3, 4, 5]

# Calculate product (multiply all)
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 120

# Calculate sum
total = reduce(lambda x, y: x + y, numbers)
print(total)    # 15

# Find maximum
maximum = reduce(lambda x, y: x if x > y else y, numbers)
print(maximum)  # 5

📊 Real-World Examples

Data Processing

data = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 78},
]

# Extract just the scores
scores = list(map(lambda d: d["score"], data))
print(scores)  # [85, 92, 78]

# Filter passing grades (>= 80)
passing = list(filter(lambda d: d["score"] >= 80, data))
print(passing)
# [{'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 92}]

Sorting with Key

students = [
    ("Alice", 85),
    ("Bob", 92),
    ("Charlie", 78),
]

# Sort by score
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)
# [('Charlie', 78), ('Alice', 85), ('Bob', 92)]

# Sort by name
sorted_by_name = sorted(students, key=lambda x: x[0])
print(sorted_by_name)
# [('Alice', 85), ('Bob', 92), ('Charlie', 78)]

⚠️ Lambda Limitations

Lambda functions can only contain one expression:

# ✅ Works - single expression
square = lambda x: x ** 2

# ❌ Doesn't work - multiple statements
divide = lambda x, y: (
    if y == 0:
        return "Error"
    else:
        return x / y
)

# ✅ Use regular function instead
def divide(x, y):
    if y == 0:
        return "Error"
    return x / y

🎯 When to Use Lambda

✅ Good Use Cases

  • Simple one-line transformations
  • With map(), filter(), reduce()
  • As callback functions
  • Sorting with custom key
  • Quick throwaway functions
# Good - used once with map
squared = list(map(lambda x: x ** 2, [1, 2, 3]))

# Good - sorting key
sorted_data = sorted(data, key=lambda x: x["age"])

❌ Avoid When

  • Logic is complex
  • Function is reused multiple times
  • Need multiple statements
  • Hard to understand
# Bad - should be regular function
process = lambda data: (
    validate(data),
    transform(data),
    save(data)
)

# Better - use regular function
def process(data):
    validated = validate(data)
    transformed = transform(data)
    save(transformed)
    return transformed

💡 Lambda vs Regular Function

# For simple cases, lambda is cleaner
numbers = [1, 2, 3, 4, 5]

# With lambda - concise
doubled_lambda = list(map(lambda x: x * 2, numbers))

# With regular function - verbose
def double(x):
    return x * 2

doubled_func = list(map(double, numbers))

# Both produce: [2, 4, 6, 8, 10]

🔑 Key Takeaways

ConceptRemember
LambdaOne-line anonymous function
Syntax`lambda params: expression`
map()Transform each element
filter()Keep elements matching condition
reduce()Combine all elements
WhenUse for simple, one-off functions
AvoidComplex logic, multiple statements

🔗 What's Next?

Now that you know lambda functions, explore decorators to enhance function behavior with elegant patterns.

Next: Decorators →


Practice: Lambda challenges


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn