All Courses
Advanced Python

Python Lambdas

What is a Lambda?

A lambda is a one-line, anonymous function — a function with no name, defined right where it's going to be used.

Traditional Function Lambda
Has a name ❌ (anonymous)
Multi-line body ❌ (one expression only)
Explicit return ❌ (expression is auto-returned)
Used where defined Sometimes ✅ (main purpose)

Syntax

lambda parameters : expression
  • Everything after the : is evaluated and automatically returned
  • Parameters work exactly like a normal function (including defaults)
lambda x, y, z=0 : x + y + z

Storing a Lambda in a Variable

func = lambda x, y, z=0 : x + y + z

print(func(1, 2))      # 3
print(func(1, 2, 4))   # 7

Guide: func is just a variable holding the function — the lambda itself has no name.


What Gets Returned

The expression after : is always returned — even if it's a call to another function:

func = lambda x, y : print(x + y)   # returns None (what print() returns)
result = func(1, 2)                  # prints 3, but result is None

Main Use Case — Inline Key Function

The primary purpose of a lambda is to define a short function right where it's needed, rather than defining a separate named function above.

Without lambda

def sort_func(x):
    return x[1]

lst = [(1, 2), (-2, -4), (3, 4), (0, 0)]
lst.sort(key=sort_func)
print(lst)   # [(-2, -4), (0, 0), (1, 2), (3, 4)]

With lambda ✅

lst = [(1, 2), (-2, -4), (3,4), (0, 0)]
lst.sort(key=lambda x: x[1])
print(lst)   # [(-2, -4), (0, 0), (1, 2), (3, 4)]

The lambda is defined exactly where it's used — cleaner and more concise.


Lambda Returning a Lambda

A lambda (or any function) can return another function. The returned function can use parameters from the outer function:

mul = lambda x : (lambda y : x * y)

result = mul(2)      # result is now a function: lambda y: 2 * y
print(result(3))     # 6
print(result(4))     # 8

Chained call (shorthand)

print(mul(5)(4))     # 20  — calls mul(5) then calls the returned function with 4

Equivalent with traditional functions

def mul(x):
    def mul2(y):
        return x * y
    return mul2

result = mul(5)
print(result(2))   # 10

Both approaches return a new customized function based on the first argument passed — this pattern is explored further in topics like closures and decorators.


Key Takeaways & Recap

Concept Summary
Lambda One-line anonymous function; expression is auto-returned
Syntax lambda params : expression
No return needed The expression result is returned automatically
Main use case Passing a short function as an argument (e.g. key= in sort)
Can have defaults lambda x, y=0 : x + y works fine
Can return a lambda Useful for building customized functions dynamically
Chained calls func(a)(b) — call the result of the first call with a second argument