Skip to content

Lambda Functions

A Lambda Function is a small, anonymous function defined without a name. While standard functions are defined using the def keyword, lambdas use the lambda keyword.

In Python, lambdas are a “syntactic sugar” for creating simple, one-off functions, primarily used as arguments for higher-order functions.


Syntax: lambda arguments: expression

  1. Anonymous: They don’t have a name unless you assign them to a variable.
  2. Single Expression: A lambda can only contain one expression. It cannot contain statements (like if-else blocks, for loops, or return).
  3. Implicit Return: The result of the expression is automatically returned.
lambda_vs_def.py
# Standard
def square(x):
return x * x
# Lambda
sq = lambda x: x * x

2. Functional Patterns: Map, Filter, and Sort

Section titled “2. Functional Patterns: Map, Filter, and Sort”

Lambdas shine when passed into functions that expect another function as an argument.

You can tell the .sort() method exactly how to compare items.

sorting.py
data = [("Alice", 88), ("Bob", 95), ("Charlie", 82)]
# Sort by the score (index 1 of the tuple)
data.sort(key=lambda item: item[1])
# Result: [('Charlie', 82), ('Alice', 88), ('Bob', 95)]
  • map(): Applies the lambda to every item in an iterable.
  • filter(): Keeps only items where the lambda returns True.
functional.py
nums = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, nums))
squares = list(map(lambda x: x ** 2, nums))

Is a lambda different from a normal function? No.

When Python executes a lambda expression, it creates a standard Function Object in memory, exactly like def does. You can even inspect its properties:

f = lambda x: x + 1
print(type(f)) # <class 'function'>
print(f.__name__) # <lambda>

The only difference is that the __name__ attribute is set to <lambda> and the object doesn’t have a docstring or type annotations.


While lambdas are powerful, they are often overused by beginners.


Featuredef Functionlambda Function
SyntaxMulti-line.Single-line expression.
NameExplicitly named.Anonymous.
CapabilityAny statement/logic.Expression only.
ReturnRequires return.Implicit return.
DocstringsSupported.Not supported.
TracebacksShows function name.Shows <lambda>.