Lambda Functions in Python

Lambda Functions in

Lambda Functions in Python

A Python lambda function is a concise way to create a small, anonymous function when you need a simple operation without defining a full function with def. A lambda can accept any number of arguments, but its body must contain a single expression whose result is returned automatically. In this guide, you will learn the syntax of lambda functions and see how they work with map, filter, reduce, sorted, and other common Python features. You will also learn their limitations, common mistakes, and when a regular def function is the better choice.

(lambda x: x * 2)()42
Change x and the lambda runs again.

What is a lambda function in Python?

A lambda function is a small, anonymous function used for a simple task. It is written with the lambda keyword, followed by the function parameters, a colon (:), and a single expression. When the lambda function is called, Python evaluates that expression and automatically returns its result.

Lambda functions are also called lambda expressions or anonymous functions. They are particularly useful when another function expects a short function as an argument. For example, you can use a lambda with the key parameter of sorted() to tell Python which value should be used for sorting. The example below breaks a lambda function into its individual parts so that you can understand how each part works.

AnatomySelect a part of the lambda

def add(x, y):
    return x + y

The following example performs the same task in two different ways. Both versions accept two numbers, add them together, and return the result. Calling add(2, 3) produces 5 in either case.

# lambda
add = lambda x, y: x + y

# def
def add(x, y):
    return x + y

add(2, 3)   # 5 either way

Three facts to remember

  • A lambda contains one expression, and Python automatically returns the value produced by that expression.
  • A lambda is a regular function object, so it can be stored, passed to another function, or called immediately.
  • Lambdas are most useful for short, simple tasks. If the logic becomes longer, more complex, or needs to be reused, a def function is usually clearer.

Python lambda syntax and rules

The basic syntax of a lambda function is simple and easy to remember:

lambda parameters: expression

What a lambda can do

  • Take no parameters, one parameter or many: lambda: 42, lambda x: x, lambda x, y: x * y.
  • Use default values: lambda base, exp=2: base ** exp.
  • Collect extra arguments with *args and **kwargs.
  • Choose between two results with a conditional expression: lambda n: "even" if n % 2 == 0 else "odd".
  • Call other functions, including print(), because a call is an expression.

What a lambda cannot do

  • Contain statements such as return, pass, raise, import or a for loop.
  • Assign with =. The walrus operator := inside parentheses is the one exception.
  • Carry type hints or a docstring.
add = lambda a, b: a + b
greet = lambda name="world": f"Hello, {name}!"
print(add(2, 3))
print(greet())
greet("Python")
Rule of thumb

If a lambda starts becoming difficult to understand or you need more than one statement, it is usually better to use def.

Try Python lambda functions in a live playground

Use the playground to experiment with the examples in this guide. Edit the code and select Run to see the result. The playground supports lambda functions, common built-in functions, list comprehensions, f-strings, and several string, list, and dictionary methods used in the examples. It does not support regular def functions, loops, or most imports, except from functools import reduce. The value of the final expression is displayed automatically, similar to a notebook cell.

PlaygroundCtrl or Cmd + Enter to run
Output

Lambda with map(), filter() and reduce()

The functions map(), filter(), and reduce() all work with another function and a collection of values. Lambda functions are useful here because they allow you to define a short operation directly where it is needed.

  • map(function, items) applies the function to each item and produces the transformed values.
  • filter(function, items) keeps only the items for which the function returns a truthy value.
  • reduce(function, items) combines the items step by step to produce a single final value. It is available from the functools module, so it must be imported before use.
from functools import reduce
nums = [1, 2, 3, 4, 5, 6]
squares = list(map(lambda n: n * n, nums))
evens = list(filter(lambda n: n % 2 == 0, nums))
total = reduce(lambda acc, n: acc + n, nums)
print(squares)
print(evens)
total

The example produces the squares of the numbers, keeps only the even numbers, and then adds all the numbers together. The results are [1, 4, 9, 16, 25, 36], [2, 4, 6], and 21. Use the explorer to see how each value moves through the selected lambda operation.

Pipeline explorerPick a tool, edit the lambda

      

Why does map() print a map object?

In Python 3, map() and filter() return lazy iterators instead of immediately creating a list. Therefore, printing the result directly displays an iterator object rather than the actual values. If you want to see all the values at once, convert the result to a list using list(). The exact memory address shown for the iterator can be different on each system.

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

The last example uses a list comprehension. In many situations, a comprehension is easier to read than combining map() or filter() with a lambda. A good rule is to use map() or filter() when you already have a suitable named function, and consider a comprehension when you would otherwise need a lambda.

Sorting with a lambda as the key

One of the most common and useful applications of a lambda function is as the key argument of sorted(), list.sort(), min(), and max(). Python applies the key function to each item and uses the returned value to determine the order or selection. Python's sorting algorithm is stable, which means that items with equal keys retain their original order.

When you need to sort by more than one field, return a tuple containing the values in the order of priority. For numeric fields that should be sorted in descending order within that tuple, you can use a negative value. Try the presets below and then create your own sorting key.

Sort explorerEach row is a dict called r

      
#NameDeptAgeSalaryKeyWas
scores = {"asha": 82, "ben": 91, "chitra": 77}
print(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))
max(scores, key=lambda name: scores[name])
Tip

For simple lookups, str.lower works as a key for case-insensitive sorting and operator.itemgetter("salary") picks a field. Both are shorter than the equivalent lambda and just as clear.

Conditionals, default arguments and *args in a lambda

A lambda cannot contain a normal if statement, but it can use a conditional expression to choose between two values. If you need more than two possible results, conditional expressions can be chained, although a regular def function may be easier to read.

sign = lambda n: "positive" if n > 0 else "negative" if n < 0 else "zero"
[sign(n) for n in [5, -2, 0]]

Lambda functions can also use default arguments and variable-length arguments in much the same way as regular functions defined with def.

power = lambda base, exp=2: base ** exp
total = lambda *nums: sum(nums)
print(power(5))
print(power(2, 10))
print(power(exp=3, base=4))
total(1, 2, 3)

If a lambda function is called with the wrong number of arguments, Python reports the function as <lambda> in the error message. Try (lambda x, y: x + y)(1) in the playground to see an example.

Where lambda functions show up in real code

Lambda functions are not limited to sorting. They are useful whenever a Python API expects a short callback function that performs a simple operation.

Transforming a pandas column

df["price_with_tax"] = df["price"].apply(lambda p: round(p * 1.2, 2))

Button callbacks in tkinter

A callback in this example does not receive arguments directly, so the lambda is used to call another function with the required value.

Button(root, text="Save", command=lambda: save_file(path))

Default values in a dictionary

from collections import defaultdict

counts = defaultdict(lambda: 0)
counts["python"] += 1

Picking the best item

words = ["pear", "fig", "banana", "kiwi"]
print(max(words, key=lambda w: len(w)))
print(min(words, key=lambda w: len(w)))
sorted(words, key=lambda w: (len(w), w))

The closure trap: lambdas created in a loop

A common problem occurs when lambda functions are created inside a loop. A lambda normally looks up the value of a variable when the lambda is called, not when it is created. As a result, several lambdas created in the same loop may all use the final value of the loop variable.

funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
fixed = [lambda i=i: i for i in range(3)]
[f() for f in fixed]

The first list produces [2, 2, 2] because every lambda reads i after the loop has completed. The second produces [0, 1, 2] because the default argument i=i stores the current value when each lambda is created. Another solution is to use functools.partial, which can avoid the need for a lambda.

Lambda vs def: which should you use?

Both lambda and def create ordinary Python function objects. The main difference is how much logic you can express and how easy the resulting code is to read, test, maintain, and debug.

lambdadef
BodyOne expressionAny number of statements
NameNone. Shows as <lambda> in tracebacksA real name
Docstring and type hintsNot supportedSupported
SpeedEquivalent in practiceEquivalent in practice
Best forShort callbacks and key functionsAnything reused, tested or longer than a line

PEP 8, the official Python style guide, recommends using def instead of assigning a lambda function to a variable. A named function is easier to understand and produces more meaningful names in error messages. Tools such as pycodestyle also report this pattern as warning E731.

# Avoid
square = lambda x: x ** 2

# Prefer
def square(x):
    return x ** 2

# Fine: the lambda is used inline and never named
sorted(points, key=lambda p: p[1])

Best practices for Python lambda functions

  • Keep it simple. If the expression is difficult to understand without a comment, use def and give the function a meaningful name.
  • Do not assign a lambda to a variable. Use def when the function needs a name so that tracebacks and logs are easier to understand.
  • Prefer comprehensions when they are clearer. For example, [n * n for n in nums] is often easier to read than list(map(lambda n: n * n, nums)).
  • Use existing functions when possible. Functions such as str.lower, len, operator.itemgetter, and operator.attrgetter can often do the job without requiring a lambda.
  • Avoid side effects. Lambdas that change shared state or print values inside a processing pipeline can make code difficult to understand and maintain.
  • Be careful with loop variables. If a lambda is created inside a loop, capture the current value with a default argument or use functools.partial.
  • Avoid nested lambdas. If one lambda returns another lambda, a regular def function is usually easier to read.

Quick quiz: how well do you know Python lambdas?

Test your understanding with six questions. Each question includes a short explanation so you can learn from the answer.

QuizScore 0

Python lambda functions: frequently asked questions

What is a lambda function in Python?

A lambda function is a small, anonymous function created with the lambda keyword. It can accept multiple arguments, evaluates a single expression, and automatically returns the result.

Can a Python lambda have more than one argument?

Yes. Multiple parameters are separated by commas, as in lambda x, y: x + y. Lambda functions can also use default arguments, *args, and **kwargs.

Can a lambda contain multiple statements?

No. A lambda body must contain a single expression. Statements such as return, assignment, for, and import cannot be used as statements inside a lambda. If the logic requires multiple statements, use a regular def function.

Is a lambda faster than a def function?

There is no meaningful performance advantage. Both approaches create ordinary Python function objects, so the choice should mainly depend on readability and maintainability.

Can I use if and else inside a lambda?

Yes. A lambda can use a conditional expression such as lambda n: "even" if n % 2 == 0 else "odd". Python does not provide a separate elif syntax inside a lambda, but conditional expressions can be chained when necessary.

When should I avoid lambda functions?

Avoid lambda functions when the logic is complex, when the function will be reused, or when you need a meaningful name, documentation, or type hints. In those situations, a regular def function is clearer and follows the style recommended by PEP 8.

Popular posts from this blog

Python Control Flow & Loops Tutorial (2026)

Python Operators with Examples: Complete Guide for Beginners (2026)

Mastering Incident Response: Complete Guide to CrowdResponse Forensic Tool