Tutorials Logic, IN info@tutorialslogic.com

Lambda in Python Anonymous Functions

Python Lambda

A lambda is a tiny anonymous function written as one expression.

Use lambda when a short transformation is needed directly inside sorted(), map(), filter(), or another function call.

If the logic needs a name, multiple lines, error handling, or explanation, a normal def function is clearer.

Lambda Function

A lambda is a small, anonymous (unnamed) function defined in a single line. It can take any number of arguments but can only have one expression. The result of the expression is automatically returned.

Syntax: lambda arguments: expression

Basic Lambda Examples

Lambda Basics

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

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

# Lambda with multiple arguments
add = lambda a, b: a + b
print(add(3, 7))   # 10

multiply = lambda a, b, c: a * b * c
print(multiply(2, 3, 4))  # 24

# Lambda with condition
is_even = lambda n: n % 2 == 0
print(is_even(4))   # True
print(is_even(7))   # False

# Immediately invoked lambda
result = (lambda x, y: x + y)(10, 20)
print(result)  # 30

Lambda with sorted()

The most common use of lambda is as a key function for sorting.

Sorting with Lambda

Sorting with Lambda
# Sort by string length
words = ["banana", "apple", "cherry", "fig", "date"]
sorted_words = sorted(words, key=lambda w: len(w))
print(sorted_words)  # ['fig', 'date', 'apple', 'banana', 'cherry']

# Sort list of dicts by a field
students = [
    {"name": "Alice", "grade": 92},
    {"name": "Bob",   "grade": 85},
    {"name": "Charlie", "grade": 97},
]
by_grade = sorted(students, key=lambda s: s["grade"], reverse=True)
for s in by_grade:
    print(f"{s['name']}: {s['grade']}")
# Charlie: 97
# Alice: 92
# Bob: 85

# Sort tuples by second element
pairs = [(1, 3), (2, 1), (3, 2)]
pairs.sort(key=lambda p: p[1])
print(pairs)  # [(2, 1), (3, 2), (1, 3)]

map filter reduce

Transform, Filter, and Reduce a Sequence

Transform, Filter, and Reduce a Sequence
numbers = [1, 2, 3, 4, 5, 6, 7, 8]

# map() - apply function to every item
squares = list(map(lambda x: x**2, numbers))
print(squares)   # [1, 4, 9, 16, 25, 36, 49, 64]

# filter() - keep items where function returns True
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)     # [2, 4, 6, 8]

# reduce() - accumulate to a single value
from functools import reduce
product = reduce(lambda acc, x: acc * x, numbers)
print(product)   # 40320 (8!)

total = reduce(lambda acc, x: acc + x, numbers)
print(total)     # 36

# Note: list comprehensions are often preferred over map/filter
squares_comp = [x**2 for x in numbers]
evens_comp = [x for x in numbers if x % 2 == 0]

Lambda vs Regular Function

Feature Lambda def Function
Name Anonymous Named
Lines Single line Multiple lines
Statements Expression only Any statements
Docstring No Yes
Best for Short, throwaway functions Reusable, complex logic

When to Use Lambda

When to Use Lambda
# Good use: short key function inline
data = [{"x": 3}, {"x": 1}, {"x": 2}]
data.sort(key=lambda d: d["x"])

# Good use: simple callback
buttons = ["OK", "Cancel", "Help"]
actions = {btn: lambda b=btn: print(f"Clicked: {b}") for btn in buttons}
actions["OK"]()  # Clicked: OK

# Bad use: complex logic (use def instead)
# Avoid this:
process = lambda x: x**2 if x > 0 else -x if x < 0 else 0

# Better as a named function:
def process(x):
    if x > 0:
        return x ** 2
    elif x < 0:
        return -x
    return 0
Lambda readability check

Can You Use Lambda Without Hiding Meaning?

5 checks
  • Name means Anonymous; a typical example is Named.
  • Lines means Single line; a typical example is Multiple lines.
  • Statements means Expression only; a typical example is Any statements.
  • Docstring means No; a typical example is Yes.
  • Lambda vs Regular Function includes Anonymous, Single line, Expression only, and No.

Lambda Decisions

0 of 2 checked

Q1. When should lambda usually be avoided?

Q2. What does key=lambda item: item["score"] usually describe?

Lambda Code That Hides Meaning

  • Using lambda for multi-step logic

    Use def when the function needs statements, validation, or a helpful name.
  • Hiding meaning inside sort keys

    Keep lambda expressions short enough that the sorting rule is obvious.
  • Calling the lambda immediately by accident

    Pass the function object where a callback is expected, not the result of calling it.

Try this next

Use a Small Inline Function

0 of 3 completed

  1. Sort a list of dictionaries by score using key=lambda item: item["score"].
  2. Take a long lambda and rewrite it as a named function.
  3. Convert a list of names to title case and decide whether list comprehension is clearer.

Lambda Use Cases

No. A lambda contains one expression. Use def when the logic needs multiple lines or clear explanation.

No meaningful beginner difference. Choose lambda for small inline expressions and def for named reusable logic.

They often appear in sorted(key=...), map(), filter(), and callback-style code where a tiny function is needed once.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.