Lambda Expressions in Python

KoshurAI
2 min readJan 5, 2023

--

In Python, a lambda function is a small anonymous function without a name. You can use lambda functions when you don’t want to use a def function for a short function.

A lambda expression is a way to create small anonymous functions in Python. They are often used as a short-hand for a function that is only used once, such as in higher-order functions like map, filter, and reduce.

Here is the general syntax for a lambda function:

lambda arguments: expression

The arguments are the variables that are passed into the lambda function. The expression is a single line of code that is executed when the lambda function is called. The value of the expression is returned by the lambda function.

Here is an example of a lambda function that takes in two arguments and returns their sum:

sum = lambda x, y: x + y
print(sum(3, 4)) # Output: 7

Here is an example of a lambda function that takes in a list and returns the list sorted in ascending order:

sort_list = lambda lst: sorted(lst)
print(sort_list([3, 4, 1, 2])) # Output: [1, 2, 3, 4]

You can also use lambda functions with higher-order functions like map, filter, and reduce.

For example, here is how you can use a lambda function with map to apply a function to each element in a list:

# Multiply each element in the list by 2
lst = [1, 2, 3, 4]
result = map(lambda x: x * 2, lst)
print(list(result)) # Output: [2, 4, 6, 8]

Here is an example of using a lambda function with filter to select elements from a list that satisfy a certain condition:

# Select elements from the list that are divisible by 2
lst = [1, 2, 3, 4]
result = filter(lambda x: x % 2 == 0, lst)
print(list(result)) # Output: [2, 4]

Finally, here is an example of using a lambda function with reduce to apply a function to the elements in a list and reduce them to a single value:

# Find the product of all elements in the list
from functools import reduce
lst = [1, 2, 3, 4]
result = reduce(lambda x, y: x * y, lst)
print(result) # Output: 24

--

--

KoshurAI
KoshurAI

Written by KoshurAI

Passionate about Data Science? I offer personalized data science training and mentorship. Join my course today to unlock your true potential in Data Science.

No responses yet