Lambda Functions in Python? - with practical example

Lambda functions in Python are anonymous functions that can have any number of arguments, but can only have one expression. They are useful when you need a simple function for a short period of time. Example 1: Adding two numbers using a lambda function Step 1: Define a lambda function that takes two arguments and returns their sum. Step 2: Call the lambda function with the desired arguments.
add = lambda x, y: x + y
result = add(5, 3)
print(result)

In this example, we define a lambda function called add that takes two arguments x and y and returns their sum. We then call the lambda function with arguments 5 and 3 , which results in 8 being printed. Example 2: Filtering a list using a lambda function Step 1: Define a list of numbers. Step 2: Use the filter function with a lambda function to filter out even numbers from the list. Step 3: Convert the filtered result into a list.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)

In this example, we have a list of numbers called numbers . We use the filter function with a lambda function to filter out even numbers from the list. The lambda function checks if a number is even by using the modulo operator % . We then convert the filtered result into a list and print it, which gives us [2, 4, 6, 8, 10] .

Comments

Popular posts from this blog

What are the different types of optimization algorithms used in deep learning?

Seven common machine learning evaluation metrics

Ten top resources for learning Python programming