Welcome to our deep dive into Python Lambda Functions! 📝
In this tutorial, we'll explore:
Lambda functions, also known as anonymous functions, are small, standalone functions that are defined without a name. They are useful when we need to perform a small task without creating a full-blown function.
In Python, lambda functions are defined using the lambda keyword, followed by a list of arguments, an equal sign, and the function's body.
## Define a lambda function that adds two numbers
add = lambda x, y: x + yLet's create a lambda function that calculates the square of a number:
## Define a lambda function that calculates the square of a number
square = lambda n: n * n
## Using the lambda function to calculate the square of 5
result = square(5)
print(result) # Output: 25We can use lambda functions with built-in functions like map(), filter(), and reduce(). Let's create a lambda function that finds the sum of all odd numbers from a list:
## Define a lambda function that checks if a number is odd
is_odd = lambda n: n % 2 != 0
## Define a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
## Using filter() with the lambda function to find odd numbers
odd_numbers = filter(is_odd, numbers)
## Using list() to convert the filter object into a list
odd_numbers_list = list(odd_numbers)
## Using sum() to calculate the sum of odd numbers
sum_of_odds = sum(odd_numbers_list)
print(sum_of_odds) # Output: 25Let's create a lambda function that calculates the product of all numbers in a list:
## Define a lambda function that takes two arguments and returns their product
multiply = lambda x, y: x * y
## Define a list of numbers
numbers = [1, 2, 3, 4, 5]
## Using map() to apply the lambda function to each pair of numbers in the list
product_pairs = map(multiply, numbers, numbers)
## Using list() to convert the map object into a list
product_pairs_list = list(product_pairs)
## Using functools.reduce() to calculate the product of all numbers in the list
import functools
product = functools.reduce(lambda x, y: x * y, product_pairs_list)
print(product) # Output: 120Python lambda functions are always anonymous and do not have an explicit return statement. They are equivalent to a function defined with the def keyword, but have some restrictions:
What is a lambda function in Python?
We hope you enjoyed learning about Python Lambda Functions! Stay tuned for more exciting topics at CodeYourCraft. Happy coding! 🚀💻🎉