Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

x = lambda a: a + 10
print(x(5))  #15

x = lambda a, b : a * b
print(x(5, 6)) #30

x = lambda a, b, c: a + b + c
print(x(5, 6, 2)) #13

lambda_cube = lambda y: y*y*y 
print(lambda_cube(5)) 

lambda with filter:

The filter() method filter in the given sequence and help of the function and test each value in sequence to be true or not and filter() method syntax is :

Syntax : filter(function, iterable)

In the first example, we pass a list of numbers and lambda function in filter and lambda function check each value modules not equal to zero and filter return an object filter after filter object convert to list and return a list of filter numbers.

In the second example pass a list of numbers and lambda function in the filter. The python lambda function filter the values have greater than 4 and returns a filter object and the filter object convert to a python list.

li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] 
final_list = list(filter(lambda x: (x%2 != 0) , li)) 
print(final_list)  #[5, 7, 97, 77, 23, 73, 61]

nums1 = [2,3,5,6,76,4,3,2]
bads = list(filter(lambda x: x>4, nums1))
print(bads)  #[5, 6, 76]

lambda with map:

The map() function similar to filter() function the map() function takes two arguments (function, iter). The map() function return a map object and map() inside lambda function test each value of list is true or not.

example 1 : Return a squares list of li list using map() function.

example 2: Convert each item of the list in uppercase using map() function.

example 3: Add two lists using map and lambda.

li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] 
final_list = list(map(lambda x: x*2, li)) 
print(final_list)    #[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]

ani = ['dog', 'cat', 'parrot', 'rabbit'] 
up_animals = list(map(lambda animal: str.upper(animal), ani)) 
print(up_animals)  #['DOG', 'CAT', 'PARROT', 'RABBIT']

numbers1 = [1, 2, 3] 
numbers2 = [4, 5, 6] 
result = map(lambda x, y: x + y, numbers1, numbers2) 
print(list(result))  #[5, 7, 9]

lambda with reduce:

The reduce() function takes two arguments (function, iter) and reduce apply a lambda function on all of the list elements. if you want to use reduce import functools because reduce() defined in functools module.

working of reduce() function:

  1. reduce takes two elements of list in sequence and apply a lambda function and result is obtained.
  2. apply the same function on previously stored results with a new iterator value and the result is again stored.
  3. The process continues till no more items left in the list.
  4. After the final result is return and print.

reduce example 1 : reduce function add two values of the list like 5+8=13 and result 13 is stored. Take new element in iteration 10 and add in stored results like 13+10=23 and process continue till end of the list like 23+20=43,43+50=93 and last is 93+100=193.

reduce example 2 : Take first two values and check condition 1>3 and result 3 stored and again check 3>5 and 5 stored same , 5>6 stored 6, 6>2 the 6 is greater than 2 and the final result is 6.

from functools import reduce
li = [5, 8, 10, 20, 50, 100] 
sum = reduce((lambda x, y: x + y), li) 
print (sum)  #193


import functools 
lis = [ 1 , 3, 5, 6, 2, ]  
# using reduce to compute maximum element from list 
print (functools.reduce(lambda a,b : a if a > b else b,lis))   #6

Filter() method in python

The filter method helps the function test each element in the sequence to be true or not. the filter function same as a map function the filter function works on logical conditions. and will eliminate the items if the condition is not true.

Syntax : filter(function, iterable)

Here is some examples of filter() method.

seq = [0, 1, 2, 3, 5, 8, 13] 
result = filter(lambda x: x % 2 != 0, seq)
print(list(result)) #[1, 3, 5, 13]

#How filter() works for iterable list?
def fun(variable): 
    letters = ['a', 'e', 'i', 'o', 'u'] 
    if (variable in letters): 
        return True
    else: 
        return False
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r'] 
filtered = filter(fun, sequence)
print('The filtered letters are:') 
for s in filtered: 
    print(s)

How filter() method works without the filter function?

randomList = [1, 'a', 0, False, True, '0']

filteredList = filter(None, randomList)

print('The filtered elements are:')
for element in filteredList:
    print(element)

The filtered elements are:
1
a
True
0

python Map() function in python

The python map() function takes two arguments first one is a function and the second one is an iterator. The map() function executes a specified function for each item in iterable. and item sends to function as a parameter.

Syntax : map(function, iterables)

Some examples of map() function.

def addition(n): 
    return n + n  
numbers = (1, 2, 3, 4) 
result = map(addition, numbers) 
print(list(result))  #[2, 4, 6, 8]

map() with lambda function

numbers1 = [1, 2, 3] 
numbers2 = [4, 5, 6] 
result = map(lambda x, y: x + y, numbers1, numbers2) 
print(list(result))

Output:
[5, 7, 9]


2)
def calculateSquare(n):
    return n*n

numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)

# converting map object to set
numbersSquare = set(result)
print(numbersSquare)

#lambda with map:
numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result)

# converting map object to set
numbersSquare = set(result)
print(numbersSquare)

Passing Multiple Iterators to map() Using Lambda:

num1 = [4, 5, 6]
num2 = [5, 6, 7]
result = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result))  #[9, 11, 13]

def myMapFunc(list1, tuple1):
    return list1+"_"+tuple1

my_list = ['a','b', 'b', 'd', 'e']
my_tuple = ('PHP','Java','Python','C++','C')

updated_list = map(myMapFunc, my_list,my_tuple)
print(updated_list)
print(list(updated_list))   #['a_PHP', 'b_Java', 'b_Python', 'd_C++', 'e_C']

Now Lambda, map, filter function is completed. If you like the article share it with your friends. if you have any question or query related to the article and have any suggestions please leave in the comment box.

Thanks for reading the Article.

Leave a Reply

Your email address will not be published. Required fields are marked *