Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

A Python lambda is a compact way to create a function for a single expression: lambda parameters: expression. The expression’s value is returned automatically. Lambdas are most useful inline, such as the key function passed to sorted(); use a named def when the operation needs several statements, annotations, reuse, or a descriptive name.

What a lambda function is

A lambda expression creates a function object. It does not execute the function immediately; execution happens when you call the resulting object.

add = lambda a, b: a + b
print(add(3, 4))  # 7

Here, a and b are parameters, and a + b is the one expression that supplies the return value. The equivalent named function is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def add(a, b):
    return a + b

Both versions return the same result. The def version gives the function a descriptive name and provides a normal suite in which you can write multiple statements.

Lambda syntax and rules

lambda parameters: expression
  • The lambda keyword starts the expression.
  • Parameters appear before the colon and follow ordinary function argument rules.
  • The body must be exactly one expression.
  • The expression’s value is returned implicitly; do not write return.
  • A lambda cannot contain statements such as for statements, try, or assignments, and it does not support function annotations.

Because a lambda is an expression, you can assign it to a variable, pass it as an argument, store it in a data structure, or return it from another function. Parentheses can make an inline lambda easier to read when it is passed directly to another call.

Calling a lambda immediately

result = (lambda word: word.upper())("python")
print(result)  # PYTHON

In ordinary code, assigning a lambda to a descriptive variable is usually less clear than defining the function with def. Inline use is where the compact syntax is most valuable.

Using lambdas as sorting keys

The most common practical use is supplying a short key function to sorted() or list.sort(). Python calls the key with each item and compares the returned values.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
students = [("Mina", 91), ("Luis", 84), ("Jo", 97)]
by_score = sorted(students, key=lambda student: student[1])
print(by_score)
# [('Luis', 84), ('Mina', 91), ('Jo', 97)]

sorted() accepts any iterable and creates a new list. The original students list remains unchanged. To sort a list in place, call sort():

students = [("Mina", 91), ("Luis", 84), ("Jo", 97)]
students.sort(key=lambda student: student[1])
print(students)
# [('Luis', 84), ('Mina', 91), ('Jo', 97)]
Operation Input Result Mutation
sorted(iterable, key=...) Any iterable New sorted list Does not change the source
some_list.sort(key=...) A list None; the list is reordered Changes the list in place

Python’s sort is stable: records with equal keys retain their original relative order. The key function is evaluated for each input item, so put the extraction logic in the key rather than repeatedly sorting with a comparison function.

Case-insensitive string sorting

For case-insensitive names, a built-in method is clearer than an equivalent lambda:

names = ["zoe", "Ada", "mira"]
sorted_names = sorted(names, key=str.casefold)
print(sorted_names)  # ['Ada', 'mira', 'zoe']

Since str.casefold is already a callable that accepts one string, no wrapper is needed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Tuple indexes and object attributes

For tuple or list indexes, operator.itemgetter() states the intent directly:

from operator import itemgetter

students = [("Mina", 91), ("Luis", 84), ("Jo", 97)]
by_score = sorted(students, key=itemgetter(1))

For objects with named attributes, use operator.attrgetter():

from operator import attrgetter

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

students = [Student("Mina", 21), Student("Luis", 19)]
by_age = sorted(students, key=attrgetter("age"))

A lambda remains useful when the key combines fields or performs a small calculation that would be less readable with a generic getter.

Small transformations and predicates

A lambda can be supplied anywhere an API expects a callable. For a short transformation, keep the operation visible at the call site:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
prices = [10, 15, 8]
with_tax = list(map(lambda price: price * 1.2, prices))
print(with_tax)  # [12.0, 18.0, 9.6]

For straightforward collection work, a comprehension is often easier to scan:

with_tax = [price * 1.2 for price in prices]

The same rule applies to predicates used for filtering: choose the form that makes the operation immediately understandable. A lambda is not automatically better merely because it is shorter.

Lambdas, closures, and surrounding variables

A lambda can read variables from its containing scope. Returning one from another function creates a closure that remembers that value:

def make_multiplier(factor):
    return lambda number: number * factor

twice = make_multiplier(2)
print(twice(5))  # 10

The returned function still has access to factor after make_multiplier() has finished. This pattern is useful for generating small, specialized callables.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A common late-binding surprise

When lambdas are created inside a loop, they read a captured variable when they are called, not necessarily when they are created. Bind the current value as a default argument when that is the intended behavior:

functions = [lambda value=i: value for i in range(3)]
print([function() for function in functions])  # [0, 1, 2]

For more involved state or control flow, a named function or a small class makes the behavior easier to explain and maintain.

Lambda versus def: a practical decision guide

Question Prefer a lambda Prefer def
How long is the logic? One short, obvious expression Several operations or branches
Will it be reused? One local call site Multiple call sites or a public API
Does it need a name? The surrounding call explains it A descriptive name improves readability
Are annotations needed? No Yes; use a normal function definition
Would a built-in express it better? Only when no clearer callable exists Use a built-in, module function, loop, or comprehension when that is clearer

The choice is primarily stylistic. If a reader must mentally decode a long lambda, replace it with def, a comprehension, a loop, or an existing built-in. A function name also gives tracebacks and debugging output more useful context.

Debugging and troubleshooting

SyntaxError near the colon

Check that the expression has the form lambda parameters: expression. A lambda body cannot contain a statement block or a second top-level statement separated by a semicolon.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“Lambda takes the wrong number of arguments”

Inspect the API that calls your function. A sorting key receives one item, so key=lambda item: ... is correct. A callback that supplies two arguments requires two parameters. Test the callable directly with a representative input.

Unexpected None from sorting

list.sort() reorders the list in place and returns None. Do not assign its return value as though it were the sorted list. Use sorted_list = sorted(items, key=...) when you need a new list.

Items are in the wrong order

Print the key values to see what Python is comparing:

for student in students:
    print(student, student[1])

Verify the index or attribute and decide whether you need reverse=True. For text, consider str.casefold rather than a case-sensitive comparison.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The lambda is difficult to test

Assign the callable temporarily and call it with small inputs, or promote it to a named def. Once the logic needs its own tests or documentation, the named version is usually the better design.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, readability, and reliability notes

There is no general performance guarantee that a lambda is faster than def; both create callable function objects and the operation inside the function determines most of the work. For sorting, Python evaluates the key for each item and then sorts the resulting keys. Avoid expensive repeated work inside a key when you can precompute a value or use a simpler callable.

Keep lambdas short enough to understand without reformatting them. Give the surrounding data and the parameter meaningful names, and use parentheses when a lambda is nested in a larger expression. Do not hide side effects in a key or predicate: a sorting or filtering callback is easiest to reason about when it only computes and returns a value.

Or skip the browser setup

If your Python project needs website screenshots for documentation, testing, or data workflows, ScreenshotNeo provides a single HTTP request instead of requiring you to install and manage a browser. It accepts cookie and consent banners like a visitor, removes more than 60 known consent platforms plus newsletter popups and chat widgets before capture, and lets you turn each cleanup step off.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Only clean shots are billed. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo API documentation for all 63 options, including full-page captures with lazy images, CSS-selector element shots, dark mode, device presets, retina scale, PDFs, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, cache TTLs, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage data, and the OpenAPI specification. Every feature is available on every plan. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Frequently Asked Questions

Can a lambda contain an if/else decision?

It can contain a conditional expression such as lambda n: "even" if n % 2 == 0 else "odd", but not a statement-style if block. Use def when the condition becomes difficult to read.

How do I sort in descending order with a lambda key?

Pass reverse=True, for example sorted(students, key=lambda student: student[1], reverse=True).

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can I add a docstring to a lambda?

Lambdas do not provide the normal structure for a function docstring. If documentation is important, define a named function with def.

Does assigning a lambda to a variable make it equivalent to a named function?

It creates a callable variable, but the function remains anonymous in its definition and is generally less descriptive in tracebacks and documentation than a function declared with def.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.