Lambda, Map, and Filter Function in Python

Understanding Lambda, Map, and Filter functions in Python with examples.

Viral Prajapati
2 min readApr 9, 2023
Photo by Rubaitul Azad on Unsplash

Lambda Function:

A Lambda function is also known as an Anonymous function. This function is declared using lamda keyword and it takes any number of parameters and returns the result based on the expression given.

For example:

# Function declaration
fun = lambda x: x**2

# Function is called
print(fun(2))

# Output: 4


# Lamda function can have any number of parameters, For example
fun2 = lambda x, y: x+y

print(fun2(2,3))

# Output: 5

Lambda Function can be used with map and filter functions, but before jumping into that first, let’s understand these two functions.

Map Function:

A Map function is applied on iterables like lists, tuples, dictionaries, sets, and strings objects. The map function takes two arguments, map(function, iterables). The function is applied on each element of the iterables and returns a new list based on the function given.

For example:

lst = [1,2,3,4,5]

squre_element = map(lambda x: x**2, lst) # returns map object

new_lst = list(squre_element) # typecast into list

print(new_lst)

# Output: [1, 4, 9, 16, 25]

# In above code, each of the list element is applied on lambda function and return the new list with squred elements.

Filter Function

Similar to the Map function, the Filter function also takes two arguments but the only difference is that it filters the element based on the function given and returns the updated list.

For example:

lst = [1,2,3,4,5]

new_lst = list(filter(lambda x: (x%2)==0, lst))

print(new_lst)

# Output: [2, 4]

# In above code, lambda function gives true if the list element is even and that is stored in a new_lst.

Conclusion:

In conclusion, Lambda is one linear or anonymous function that returns results based on the expression. Map function iterates through iterable and returns an updated list, whereas Filter function works the same except it filters the list based on the given function.

Thank you for reading!!!

--

--

Viral Prajapati
0 Followers

Aspiring Data Scientist | Software Developer