Python Lambda & Anonymous Functions: Syntax, Examples, map(), filter(), sorted()

Learn Python lambda functions (anonymous functions): syntax, examples with multiple arguments, map(), filter(), sorted(), conditional expressions, limits, common mistakes, and when to use def instead.

Published

Updated

Read time 6 min read

Reviewed byDeepak Prasad

Python Lambda & Anonymous Functions: Syntax, Examples, map(), filter(), sorted()

People search for both Python lambda functions and anonymous functions in Python—they are the same feature: a function object you build with the lambda keyword, usually in one line, without a separate def block. Lambdas work well as the key to sorted, or as the callable passed to map and filter, when the logic stays a single expression. This guide covers syntax, lambda with multiple arguments, conditional expressions, builtins, limits, and when a named function is clearer.

For general function definitions, see Python functions. For list-style transforms, see list comprehension. For iterable yes/no checks with the built-in any() and all(), see Python any() and all().

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


What is a Python lambda (anonymous function)?

An anonymous function is simply a function without a name in your source at the point of definition. In Python you create that object with lambda, so terms like “lambda function,” “anonymous function,” and “anonymous lambda” describe the same mechanism. You can assign it to a name (square = lambda x: x * x) or pass it directly (sorted(items, key=lambda t: t[1])). In tracebacks the name often appears as <lambda>, which is one reason longer logic is usually clearer as a def with a real identifier.


Python lambda function syntax

The grammar is:

text
lambda parameters: expression

parameters follow the same rules as a def parameter list (including defaults). expression is evaluated when the function is called and its value is returned—there is no return keyword inside the lambda.

python
square = lambda x: x * x
print(square(5))
Output

That prints 25.


Anonymous function vs regular function

A def creates a named function with a suite of statements and an optional docstring. A lambda must be a single expression; you cannot put assignment statements, try/except, for/while, or multiple logical lines in the body. For anything non-trivial, a normal function is easier to read, test, and profile.

The same “double a number” idea can be written both ways—the def can use intermediate variables and a docstring; the lambda cannot:

python
double_lambda = lambda x: x * 2

def double_def(x: int) -> int:
    """Return twice x (shows up in help() and many tracebacks)."""
    doubled = x * 2
    return doubled

print(double_lambda(3), double_def(3))
Output

Both print 6.


Create and call a lambda function

You create a lambda and call it like any callable—either immediately with parentheses or later via a variable:

python
print((lambda x: x + 1)(10))

add_one = lambda x: x + 1
print(add_one(10))
Output

Both lines print 11.


Lambda function with one or more arguments

A lambda with multiple arguments uses commas in the parameter list, just like def:

python
pair = lambda a, b: (a + b, a * b)
print(pair(3, 4))

with_default = lambda x, y=10: x + y
print(with_default(5))
print(with_default(5, 1))
Output

The first call prints (7, 12); the second shows default y: 15 then 6.


Lambda function with if else expression

Use Python’s conditional expression (ternary), not an if block:

python
clip = lambda x, lo, hi: lo if x < lo else hi if x > hi else x
print(clip(99, 0, 10))
Output

Output is 10. For multiple branches, a def with real if/elif is usually clearer.


Using lambda with sorted(), map(), and filter()

These builtins take a callable; lambdas are a compact way to supply it. Prefer a def or operator helpers when the expression grows hard to scan. For dedicated guides, see Python map() and Python filter().

Lambda with sorted()

key= receives each element and should return the sort key:

python
words = ['pear', 'apple', 'plum']
print(sorted(words, key=lambda w: len(w)))

rows = [('ada', 92), ('lin', 88), ('kim', 95)]
print(sorted(rows, key=lambda t: t[1]))
Output

First line sorts by string length; second sorts tuples by the numeric score.

Lambda with map()

map(func, iterable) applies func to every item; in Python 3 you usually wrap in list to materialize:

python
nums = [1, 2, 3]
print(list(map(lambda n: n * n, nums)))
Output

Prints [1, 4, 9]. For simple transforms, a list comprehension is often more idiomatic than map with a lambda.

Lambda with filter()

filter(func, iterable) keeps items where func(item) is true:

python
nums = range(8)
print(list(filter(lambda n: n % 2 == 0, nums)))
Output

Prints even values [0, 2, 4, 6].


When to use lambda functions in Python

Use a lambda when the callable is short, local, and used once—especially as sorted(..., key=...), or a tiny predicate for filter. They keep sorting and data-shaping code on one readable line when the expression fits comfortably.

For example, pick the tuple with the largest second value without naming a helper:

python
pairs = [('a', 3), ('b', 1), ('c', 2)]
print(max(pairs, key=lambda t: t[1]))
Output

Prints ('a', 3).


When not to use lambda functions

Skip lambdas when the logic spans more than a small expression, when you need loops, exception handling, or reuse in several places, or when a name and docstring help your team navigate the codebase. Promote the logic to a def (or a small functools.partial around an existing named function).

Compare filtering rows: a real if branch and reuse are clearer in a def than in a nested conditional inside a lambda:

python
rows = [('app.py', 120), ('notes.txt', 0), ('util.py', 45)]

def is_nonempty_python(path: str, size: int) -> bool:
    if not path.endswith('.py'):
        return False
    return size > 0

print([r for r in rows if is_nonempty_python(*r)])
Output

Prints [('app.py', 120), ('util.py', 45)]. You could force that into a lambda, but the def stays obvious when you extend the rule (logging, try/except, etc.).


Limitations of Python lambda functions

  • Only one expression in the body—no statements; the walrus := is an expression but rarely improves clarity inside lambdas.
  • No docstring attached in the usual way; tracebacks show <lambda>.
  • Harder to unit-test in isolation than a named function on a module.
  • Deeply nested lambdas are almost always harder to read than nested defs.

Common mistakes with anonymous functions and lambdas

  • Capturing a loop variable too late in a list of lambdas—every closure sees the final loop value unless you bind with a default argument, for example [lambda i=i: i for i in range(3)].
  • Stacking map/filter/lambda into one unreadable line; split into steps or use comprehensions.
  • Using a lambda where operator.itemgetter or operator.attrgetter would be clearer for sort keys (for example key=itemgetter(1) on tuples).

Lambda vs def in Python

Concern lambda def
Body Single expression Full statement suite
Name in code Optional; often inline Required
Docstring / introspection Weak Strong
Reuse across modules Awkward Natural

Rule of thumb: if you hesitate naming it, start with def and a one-line return.


Python lambda and anonymous function quick reference table

Pattern Example
Identity lambda x: x
Two args lambda a, b: a + b
Default arg lambda x, y=1: x + y
Ternary lambda x: 'neg' if x < 0 else 'pos'
Sort key sorted(items, key=lambda x: x[1])
Map list(map(lambda n: n * 2, nums))
Filter list(filter(lambda n: n > 0, nums))

Summary

Python lambda functions are the language’s anonymous functions: expression-only callables you define with lambda, including multiple arguments and defaults when needed. They fit sort keys and short map/filter predicates; they do not replace full def functions for branching, loops, or reusable logic. Use them when brevity helps; use named functions (or comprehensions and operator helpers) when readability, testing, or tracebacks matter more than saving a few lines.


References


Frequently Asked Questions

1. What is an anonymous function in Python?

It is a function object without a name at the point you define it; in Python you almost always create that object with the lambda keyword, so “anonymous function” and “lambda function” refer to the same idea.

2. What is a lambda function in Python?

A small inline function written as lambda parameters: expression—parameters work like def, but the body must be a single expression whose value is returned implicitly.

3. Can a Python lambda have multiple arguments or default values?

Yes—use commas between parameters like lambda x, y, z=1: x + y + z; defaults and keyword arguments at the call site work like a normal function, but the body must stay one expression.

4. Can a lambda contain if statements or loops?

No multi-line blocks or statements—only one expression; use a conditional expression (a if cond else b) or a def when you need branches, loops, or multiple steps.

5. When should I use a lambda instead of def?

Use a lambda for a tiny, throwaway callable passed once (sort key, short map/filter predicate); use def when the logic is longer, reused, or needs a name for debugging and docstrings.

6. Are lambdas faster than normal functions?

Runtime cost is essentially the same for simple calls; choose between them for readability and stack traces, not micro-performance.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …