Lambda function and comprehension in Python | Complete Python Course | Data Science In Hindi | Python Tutorial In Hindi
In Python, a lambda function, also known as an anonymous function or a lambda expression, is a small, inline function defined using the lambda keyword. Lambda functions are often used when you need a simple function for a short period and don't want to define a full-fledged function using the def keyword.
The syntax of a lambda function is:
code
lambda arguments: expression
• lambda: This is the keyword used to define a lambda function.
• arguments: These are the input parameters of the function. You can have zero or more arguments separated by commas.
• expression: This is a single expression that represents the computation performed by the function. The result of this expression is implicitly returned.
Here's an example of a lambda function that adds two numbers:
pythonCopy code
add = lambda x, y: x + y # Example usage result = add(3, 5) print(result) # Output: 8
In this example:
• The lambda function lambda x, y: x + y takes two arguments x and y.
• The expression x + y adds the two input numbers.
• We assign this lambda function to the variable add.
• We then call the add function with arguments 3 and 5, which returns 8.
Lambda functions are often used in conjunction with built-in functions like map(), filter(), and reduce(), or within list comprehensions, where a function is required but a full-fledged function definition would be overly verbose. For example:
code
Using lambda function with map() numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) print(squared) # Output: [1, 4, 9, 16, 25]
Lambda functions are concise and powerful, but they should be used judiciously. While they can make code more readable for simple operations, they can also make code harder to understand if overused or used inappropriately. Therefore, it's essential to strike a balance between readability and conciseness when using lambda functions.
Explain Python in Hindi | Data Analytics Tutorial | Data Science Tutorial