A lambda function in Python is a small, anonymous function defined using the lambda
keyword. Unlike regular functions created with def
, a lambda function can have any number of arguments but only a single expression, which is evaluated and returned. It is commonly used for short, simple operations where defining a full function would be unnecessary. Lambda functions are often used in functional programming with built-in functions like map()
, filter()
, and sorted()
. For example, a lambda function that adds two numbers can be written as add = lambda x, y: x + y
, and calling add(3, 5)
returns 8
. Another example is sorting a list of tuples based on the second element using sorted(data, key=lambda x: x[1])
. Lambda functions help keep code concise and improve readability in situations where a quick, one-time function is needed.