Lambda Reference
Anonymous single-line expression functions.
Define anonymous small functions.
Used In: Key sorting metrics (e.g. sorted(d, key=lambda x: x[1])), quick filtering.
lambda args: expressionsquare = lambda x: x * x
print(square(4))16Time Complexity: O(1)
Common Mistakes: Using lambda for complex functions reduces code readability.
Related Methods: map(), filter()
def function vs lambda: def defines a reusable, named function with multiple statements; lambda defines an anonymous, inline single-expression function.
Apply a lambda transformation function to all elements in an iterable.
Used In: Converting currencies, converting list elements to uppercase.
map(lambda item: expr, iterable)lst = [1, 2, 3]
res = map(lambda x: x * 10, lst)
print(list(res))[10, 20, 30]Time Complexity: O(N)
Related Methods: filter()
map() vs list comprehension: list comprehensions are often preferred for readability and slightly better speed in modern Python.
Filter out items in an iterable using a truthy conditional lambda predicate.
Used In: Cleaning invalid data rows, selecting active logs.
filter(lambda item: cond, iterable)lst = [10, 15, 20]
res = filter(lambda x: x % 2 == 0, lst)
print(list(res))[10, 20]Time Complexity: O(N)
Related Methods: map()
Sort collections of records using a custom key accessor function.
Used In: Ordering tables by custom columns, sorting key metrics.
sorted(iterable, key=lambda x: x['key'])users = [{'name': 'A', 'sal': 30}, {'name': 'B', 'sal': 10}]
print(sorted(users, key=lambda x: x['sal']))[{'name': 'B', 'sal': 10}, {'name': 'A', 'sal': 30}]Time Complexity: O(N log N)
Related Methods: list.sort()
Cumulative folding operation running left-to-right across elements.
Used In: Aggregating metrics, cumulative multiplications.
functools.reduce(lambda acc, val: expr, iterable)from functools import reduce
lst = [1, 2, 3, 4]
val = reduce(lambda acc, x: acc * x, lst)
print(val)24Time Complexity: O(N)
Related Methods: sum(), math.prod()
Compare anonymous lambdas with standard def statements.
Used In: Selecting coding styles for readability.
N/A# Lambda: f = lambda x: x + 1
# Normal: def f(x): return x + 1N/ATime Complexity: O(1)