Explain Lambda Function in Python details with Code


What is Lambda Function in Python ? 

In Python, a lambda function is a small anonymous function that can have any number of arguments but can only have one expression. It is defined using the keyword "lambda" followed by the function arguments and a colon, followed by the expression to be evaluated.


Here's the syntax for defining a lambda function:

lambda arguments: expression


The lambda function can then be assigned to a variable for later use or can be used directly as a function.


Here's an example of a lambda function that adds two numbers:


sum = lambda x, y: x + y
print(sum(5, 10))   # Output: 15


In the above code, we have defined a lambda function called sum that takes two arguments x and y and returns their sum. We then call the sum function with two arguments 5 and 10, and it returns their sum, which is 15.


Lambda functions are often used in conjunction with higher-order functions like map(), filter(), and reduce(). Here's an example of using a lambda function with the map() function to convert a list of strings to uppercase:


words = ['hello', 'world', 'python']
uppercase_words = list(map(lambda x: x.upper(), words))
print(uppercase_words)   # Output: ['HELLO', 'WORLD', 'PYTHON']


In the above code, we have used a lambda function with the map() function to apply the upper() method to each string in the list words, which converts them to uppercase. The resulting list is then assigned to the uppercase_words variable and printed.


Lambda functions can be a convenient way to define small functions without having to write a separate function definition. However, they can also make code harder to read and maintain if overused. It is important to use lambda functions judiciously and only in cases where their use improves the readability and maintainability of the code.

       

Advertisements

ads