In Python, a lambda function is a small, anonymous function defined with the lambda
keyword. Unlike regular functions created with def
, lambda functions are designed for situations where you need a simple function for a short period of time and don’t need to give it a name. Lambda functions can be useful for quick, one-off operations and are commonly used in functional programming with functions like map()
, filter()
, and sorted()
.
The syntax for a lambda function is:
**lambda**
: The keyword used to define a lambda function.**arguments**
: The parameters the function accepts.**expression**
: A single expression that the function evaluates and returns.lambda x, y: x + y
creates an anonymous function that takes two arguments and returns their sum. The function is assigned to the variable add
.Lambda functions are often used with Python's built-in functions that accept other functions as arguments.
map()
The map()
function applies a function to all items in an iterable (e.g., a list).
lambda x: x ** 2
creates a function that squares its input, and map()
applies this function to each element in the numbers
list.filter()
The filter()
function filters elements from an iterable based on a function that returns True
or False
.
lambda x: x % 2 == 0
creates a function that returns True
for even numbers. filter()
uses this function to filter out odd numbers from the numbers
list.sorted()
The sorted()
function can take a key
argument to specify a function to determine the sort order.
lambda p: p[1]
creates a function that returns the second element of a tuple. sorted()
uses this function to sort the list of tuples by the second element.return
keyword.map()
, filter()
, and sorted()
.def
might be unnecessarily verbose.Lambda functions in Python provide a concise way to create anonymous functions for short-term use. Their single-expression limitation makes them ideal for simple operations and functional programming scenarios. By understanding and utilizing lambda functions effectively, you can write more concise and readable Python code, especially when working with functions that require callable objects.