Python Lambda: Beginner Python tutorials 11 | Better4Code
Python Lambda is a shorthand notation for creating small, anonymous functions in Python. In this article, we’ll explore the syntax and usage of Python Lambda functions with examples.
Defining a Lambda Function
A Lambda function is defined using the lambda keyword, followed by a comma-separated list of parameters, a colon, and the expression to be evaluated. Here’s an example:
square = lambda x: x ** 2
In this example, we have defined a Lambda function called square that takes one parameter, x. The function then returns the square of x. This is equivalent to defining the same function using the def keyword as follows:
def square(x):
return x ** 2
Using a Lambda Function
Once you’ve defined a Lambda function, you can use it just like any other function in Python. Here’s an example:
print(square(5))
Output:
25
In this example, we have called the square Lambda function with the argument 5, resulting in the value 25 being returned and printed to the console.
Lambda functions are often used as arguments to higher-order functions such as map(), filter(), and reduce(). Here’s an example using map():
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)
Output:
[1, 4, 9, 16, 25]
In this example, we have used the map() function to apply the square Lambda function to each element of the numbers list, resulting in a new list of squared numbers.
Multiple Parameters
Lambda functions can take multiple parameters by separating them with commas in the parameter list. Here’s an example:
product = lambda x, y: x * y
print(product(3, 4))
Output:
12
In this example, we have defined a Lambda function called a product that takes two parameters, x, and y. The function then returns the product of x and y. We then called the function with the arguments 3 and 4, resulting in the value 12 being printed to the console.
Conclusion
Python Lambda functions are a concise and powerful way to create small, anonymous functions in Python. They can be used to write more efficient, readable code, and are often used as arguments to higher-order functions.
While Lambda functions can be useful in certain situations, it’s important to note that they should be used sparingly and only when appropriate. In many cases, it’s better to use a regular function definition for clarity and maintainability.
Overall, understanding Lambda functions is an important part of becoming a proficient Python programmer. With the knowledge and examples provided in this article, you should now be able to write and use Lambda functions in your own Python code.