Anonymous functions, also known as lambda functions, are functions that are defined without a name. They are typically used for short, simple functions that do not need to be reused.
Here is an example of a lambda function that squares a number:
square = lambda x: x ** 2 |
In this example, lambda is used to define an anonymous function that takes a single parameter x and returns x ** 2, which is the square of x. The resulting function is assigned to the variable square.
You can then call this function with a value, like this:
result = square(4)print(result) # Output: 16 |
This will call the square function with the argument 4, which will return the value 16. The result variable will then contain the value 16, which is printed to the console using the print function.
Lambda functions can have any number of parameters, but they can only contain a single expression. They are typically used in conjunction with other functions, such as the built-in map, filter, and reduce functions, to perform simple operations on collections of data.