← Back to Python Course | Chapter 4: Functions | Lesson 7 of 9

Python Lambda Functions

What is a Lambda Function?

A lambda defines a small, unnamed function inline using the lambda keyword instead of def — it can take any number of arguments but is limited to a single expression, with no statements or multiple lines allowed.

Example: What is a Lambda Function?

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

Lambdas with filter()

filter() keeps only the items from an iterable for which a given function returns True, and a lambda is the typical way to supply that test condition inline without defining a separate named function just for one use.

Example: Lambdas with filter()

python
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)

Lambdas with map()

map() applies a function to every item in an iterable and returns the transformed results; pairing it with a lambda lets you write a quick, throwaway conversion — like doubling every number in a list — without a full function definition.

Example: Lambdas with map()

python
numbers = [1, 2, 3]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)

Lambdas with sorted()

Passing key=lambda x: x[1] to sorted() tells it to sort by a computed value rather than the item itself, which is essential when sorting tuples, dictionaries, or objects by something other than their natural order.

Example: Lambdas with sorted()

python
pairs = [(1, "b"), (2, "a")]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)

Lambdas vs Regular Functions

Lambdas are meant for short, single-expression logic; the moment you need a loop, error handling, or more than one statement, a regular def function is clearer and should be preferred over forcing that logic into a lambda.

Example: Lambdas vs Regular Functions

python
# Lambda: short, single expression
square = lambda x: x * x

# Regular function: clearer for multi-step logic
def square_verbose(x):
    result = x * x
    return result

print(square(4), square_verbose(4))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.