#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
7 min read
•Question 24 of 41medium

Lambda and Functional Programming

Anonymous functions and functional concepts.

What You'll Learn

  • Lambda function syntax and usage
  • Built-in functional functions: map, filter, reduce
  • When to use lambdas vs regular functions
  • functools utilities: partial, lru_cache
  • Functional programming patterns in Python

Lambda Function Basics

A lambda is an anonymous (unnamed) function defined in a single expression:

code.pyPython
# Syntax: lambda arguments: expression

# Simple lambda
square = lambda x: x ** 2
print(square(5))  # 25

# Multiple arguments
add = lambda x, y: x + y
print(add(3, 4))  # 7

# With default arguments
greet = lambda name, greeting="Hello": f"{greeting}, {name}!"
print(greet("Alice"))           # "Hello, Alice!"
print(greet("Bob", "Hi"))       # "Hi, Bob!"

# Immediately invoked
result = (lambda x, y: x + y)(3, 4)  # 7

map() - Transform Each Element

code.pyPython
# map(function, iterable) -> iterator

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

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

# 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]

# Convert types
strings = ["1", "2", "3"]
integers = list(map(int, strings))  # [1, 2, 3]

filter() - Select Elements

code.pyPython
# filter(function, iterable) -> iterator

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

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

# Remove falsy values
mixed = [0, 1, "", "hello", None, [], [1, 2]]
truthy = list(filter(None, mixed))
print(truthy)  # [1, 'hello', [1, 2]]

# Combined with map
# Get squares of even numbers
result = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, nums)))
print(result)  # [4, 16, 36, 64, 100]

reduce() - Aggregate Values

code.pyPython
from functools import reduce

# reduce(function, iterable, [initializer])

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

# Product of all numbers
product = reduce(lambda x, y: x * y, nums)
print(product)  # 120 (1*2*3*4*5)

# With initial value
total = reduce(lambda x, y: x + y, nums, 100)
print(total)  # 115 (100 + 1+2+3+4+5)

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

# Flatten nested list
nested = [[1, 2], [3, 4], [5, 6]]
flat = reduce(lambda x, y: x + y, nested)
print(flat)  # [1, 2, 3, 4, 5, 6]

sorted() with key

code.pyPython
# Sort by custom criteria

words = ["apple", "pie", "banana", "kiwi"]

# By length
by_length = sorted(words, key=lambda x: len(x))
print(by_length)  # ['pie', 'kiwi', 'apple', 'banana']

# By last letter
by_last = sorted(words, key=lambda x: x[-1])
print(by_last)  # ['banana', 'apple', 'pie', 'kiwi']

# Complex objects
users = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25},
    {"name": "Charlie", "age": 35}
]

by_age = sorted(users, key=lambda u: u["age"])
# [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, ...]

# Multiple criteria (age, then name)
sorted(users, key=lambda u: (u["age"], u["name"]))

functools Utilities

code.pyPython
from functools import partial, lru_cache, wraps

# partial - Pre-fill function arguments
def power(base, exp):
    return base ** exp

square = partial(power, exp=2)
cube = partial(power, exp=3)

print(square(5))  # 25
print(cube(3))    # 27

# lru_cache - Memoization
@lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(100))  # Instant! (cached)
print(fibonacci.cache_info())  # CacheInfo(hits=98, misses=101, ...)

# Clear cache
fibonacci.cache_clear()

Lambda vs Regular Function

AspectLambdaRegular Function
NameAnonymousNamed
SyntaxSingle expressionMultiple statements
ReturnImplicitExplicit return
DocstringsNot supportedSupported
DebuggingHarder (no name)Easier
code.pyPython
# Use lambda for simple, one-time operations
sorted(items, key=lambda x: x.priority)

# Use regular function for:
# - Complex logic
# - Reusability
# - Documentation
def calculate_score(item):
    """Calculate weighted score based on multiple factors."""
    base = item.priority * 10
    bonus = item.urgency * 5 if item.is_important else 0
    return base + bonus

sorted(items, key=calculate_score)

Comprehensions vs map/filter

code.pyPython
nums = [1, 2, 3, 4, 5]

# List comprehension (more Pythonic)
squares = [x**2 for x in nums]
evens = [x for x in nums if x % 2 == 0]

# map/filter
squares = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))

# Comprehensions are generally preferred in Python
# But map/filter can be cleaner with existing functions
list(map(str, nums))  # Cleaner than [str(x) for x in nums]

Interview Tip

When asked about lambda and functional programming:

  1. Lambda: anonymous, single expression, implicit return
  2. map transforms, filter selects, reduce aggregates
  3. Prefer comprehensions for readability in Python
  4. Use partial for fixing arguments, lru_cache for memoization
  5. Regular functions for complex logic and reusability