Hello guys, a lambda function in Python, also called an anonymous function, is a small, inline function that can be defined without a name. It is a way of creating a function that can be passed as an argument to another function or used as a one-liner. Lambda functions are typically used when you need a simple function that will be used only once and you don’t want to define a separate function for it.
The syntax for defining a lambda function is:
lambda arguments : expression
Here, arguments
are the arguments that the function takes, separated by commas, and expression
is the single expression that the function returns.
For example, consider a list of numbers and you want to sort them in descending order. You can use the sorted()
function and pass a lambda function as the key argument:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_numbers = sorted(numbers, key=lambda x: -x) print(sorted_numbers) # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
In the above example, the lambda function lambda x: -x
takes an argument x
and returns its negation (-x
). This means that the sorted()
the function will sort the numbers in descending order.
Lambda functions can also be used as a shorthand for defining simple functions. For example, the following two functions are equivalent:
def square(x): return x * x square = lambda x: x * x
So, in the end, it is generally recommended to use a regular named function for more complex logic or for functions that are used multiple times.