Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. lambda / Anonymous Functions

lambda / Anonymous Functions

lambda is a keyword that defines an anonymous function — a function without a name — in a single line. It is commonly used when passing a function object as an argument, such as the key parameter of sorted(), or the first argument of map() and filter(). A lambda body can only contain a single expression, so use a regular def when you need multiple statements.

Syntax

# Basic lambda syntax
func = lambda param1, param2: expression

# Use with sorted() key
sorted(iterable, key=lambda x: x.attribute)

# Use with map() and filter()
list(map(lambda x: transform_expression, iterable))
list(filter(lambda x: condition_expression, iterable))

Functions & Use Cases

Function / Use CaseDescription
lambda param: expressionDefines an anonymous function without a name.
sorted(iter, key=lambda)Specifies the sort key using a lambda.
sorted(iter, key=lambda, reverse=True)Sorts in descending order.
map(lambda, iterable)Returns an iterator that applies the lambda to each element.
filter(lambda, iterable)Returns an iterator of only the elements for which the lambda returns True.

Sample Code

# lambda: basic anonymous functions
square = lambda x: x ** 2
add    = lambda a, b: a + b

print(square(5))    # 25
print(add(3, 4))    # 7

# sorted: specify a sort key with lambda
fruits = ['banana', 'apple', 'cherry', 'date']
sorted_by_length = sorted(fruits, key=lambda s: len(s))
print(sorted_by_length)     # ['date', 'apple', 'banana', 'cherry']

# sorted: sort a list of dictionaries
people = [
    {'name': 'Alice', 'age': 30},
    {'name': 'Bob',   'age': 25},
    {'name': 'Carol', 'age': 35},
]
sorted_people = sorted(people, key=lambda p: p['age'])
print([p['name'] for p in sorted_people])   # ['Bob', 'Alice', 'Carol']

# sorted: sort by multiple keys (return a tuple)
data = [('Alice', 30), ('Bob', 25), ('Carol', 30), ('Dave', 25)]
# Sort by age ascending, then by name ascending
sorted_data = sorted(data, key=lambda x: (x[1], x[0]))
print(sorted_data)
# [('Bob', 25), ('Dave', 25), ('Alice', 30), ('Carol', 30)]

# map: transform each element
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, nums))
print(squares)  # [1, 4, 9, 16, 25]

# Note: a list comprehension is often more Pythonic
squares2 = [x ** 2 for x in nums]

# filter: keep only elements that match a condition
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)    # [2, 4]

# Combining filter and map
result = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, nums)))
print(result)   # [4, 16]  (squares of even numbers)

# Note: the same result with a list comprehension
result2 = [x ** 2 for x in nums if x % 2 == 0]

Notes

A lambda is essentially the same as defining a regular function with def, but its single-line form makes it convenient to pass inline as an argument. That said, when the logic is complex or you need to debug it, defining a named function with def is usually more readable.

Combining map() and filter() with lambda has long been a common Python pattern, but modern Python considers list comprehensions and generator expressions more readable, and the Python style guide (PEP 8) recommends comprehensions over map()/filter(). Reserve lambda for situations where a comprehension is not a suitable replacement, such as the key parameter of sorted().

If you find any errors or copyright issues, please .