Map Filter and Lambda Functions

Map

map() function is used to execute a function for each item in the iterable.

For a map() function, a specific function to execute and iterable will be sent as parameters.

Syntax

map(function, iterables)

map applies the function to every element of the list.

Example

def square(num):
    return(num**2)

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

print(map(square,my_nums))  # provides just address of this output, in order to view we need to convert the output as list.
print(list(map(square,my_nums)))

Result:
<map at 0x7f9a483e9ad0>
[1, 4, 9, 16, 25]

Example

def myfunc(a, b):
  return a + b

x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))

print(list(x))

Result:
['appleorange', 'bananalemon', 'cherrypineapple']

Filter

filter() function returns an iterator when the items are filtered through a function and if the function accepts the item.

Syntax

filter(function, iterables)

Example

def check_even(num):
    return num%2 == 0

mynums = [1,2,3,4,5,6]

print(filter(check_even,mynums))
print(list(filter(check_even,mynums)))

Result:
<<filter at 0x7fa8a05e6c50>>
[2, 4, 6]

Lambda

Example

def square(num):
    return num**2

# The above function can also be written as 
def square(num): return num**2

print(square(3))

when we use the function only once, we will define it as lambda.

lambda is nothing is but a simple anonymous function.

Syntax

lambda arguments : expression

lambda function can take any number of arguments, but can only have one expression.

Example

square = lambda num: num**2

square(5)

As lambda is anonymous, we generally won't give any name for it.
We will use lambda expression in map and filter functions as below

Example

list(map(lambda num: num**2, my_nums))

list(filter(lambda num: num%2 == 0, my_nums))

Example

names = ['Andy','Eve','Sally']

print(list(map(lambda name: name[0], names)))

Result: 
['A', 'E', 'S']

print(list(map(lambda name: name[::-1], names)))

Result: 
['ydnA', 'evE', 'yllaS']

The power of lambda is better shown when we use anonymous function inside another function

Example

def myfunc(n):
  return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))