Filter(), map() and reduce()

Oct. 1, 2022, 8:02 a.m.


Filter(): The filter() function construct a list from those elements of the list for which a functions return True.
The filter() function returns True or False.

Note: it is recommended to use list comprehensions instead of these functions where possible.

Filter(): The filter() function construct a list from those elements of the list for which a functions return True.
The filter() function returns True or False.

Note: it is recommended to use list comprehensions instead of these functions where possible.

# Syntax
filter(func,iterable)

Example of filter()

num=[15,20,35,2,6,12,56,89,34,23,67,10]

def greater_10(item):
    if item>10:
        return 1
    
if __name__=='__main__':
    rslt = list(filter(greater_10,num))
    print(rslt)

It will return the list with the elements greater than 10 only.

map()

The map function applies a particular funtion to every element of a list.

# Syntax
map(func,iterable)

Example of map()

num1=[15,20,35,2,6,12,56,89,34,23,67,10]

def divide_2(item):
    return item/2

if __name__=='__main__':
    new_list = list(map(divide_2,num1))
    print(new_list)

1) After applying a function on the list the map() returns a modified list.

2) You can pass any no. of iterable to map function.

      a) Function should have same no. of arguments as the no. of iterables in map function.

      b) Each argument is called with corresponding item for each sequence.

a_marks=[75,80,68,45,67,58]
b_marks=[89,67,94,50,49,79]

def compare(n,n2):
    if n>n2:
        return n
    else:
        return n2
    
if __name__=='__main__':
    max_marks = list(map(compare,a_marks,b_marks))
    print(max_marks)

reduce()

The reduce() fucntion with syntax as given below returns a single value generated by calling the function on the first two items of the iterable, then on the result and the next item.

# Syntax
from functors import reduce
reduce(func,iterable)
from functools import reduce

marks=[33,56,78,90,56,67]

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

print(reduce(add,marks))



Tags



Comments