Python Lambda Functions: A Quick Guide

Python Logo

A lambda function in Python is a small, anonymous function defined with the `lambda` keyword. It can take any number of arguments but can only have one expression. They are syntactically restricted but are handy for short, one-off functions.

Syntax

lambda arguments: expression

Standard Function vs. Lambda Function

A function to add two numbers can be written in two ways:

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

# Lambda function
add_lambda = lambda x, y: x + y

print(add(5, 3))         # Output: 8
print(add_lambda(5, 3))  # Output: 8

When to Use Lambda Functions

Lambda functions are best used when you need a small function for a short period, often as an argument to a higher-order function (a function that takes other functions as arguments). Common use cases are with `map()`, `filter()`, and `sorted()`.

Example with `sorted()`:

Sorting a list of tuples based on the second element.

points = [(1, 5), (9, 2), (4, 7)]

# Sort by the second value in each tuple (y-coordinate)
sorted_points = sorted(points, key=lambda point: point[1])

print(sorted_points) # Output: [(9, 2), (1, 5), (4, 7)]

Example with `filter()`:

Filtering out even numbers from a list.

numbers = [1, 2, 3, 4, 5, 6]

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers) # Output: [2, 4, 6]

Comments