map and filter function in python


 map function in python

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)
Syntax :
map(fun, iter)
Parameters :
fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.


# map function executes an specified function to any list or array
tup1 = ("1", "2", "3", "4")
mvar = tuple(map(int, tup1)) # all elements of tuple maped with int function and map object type casted as tuple
print(mvar)

lst = [1, 2, 3, 4, 5, 6, 7] # list
lam = lambda a: a * a # lambda function returning square of number
mvar2 = list(map(lam, lst)) # list 'lst' elements are mapped with 'lam' function and type casted as list
print(mvar2)

def add(a):
return a*a
mvar3= list(map(add, lst))
print(mvar3)


filter function in python

The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.

syntax: 
filter(function, sequence) 
Parameters:
 function: function that tests if each element of a sequence true or not. 
sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators. 
Returns: returns an iterator that is already filtered.
def red(var):
vovel=["a","e","i","o","u"]
if var in vovel:
return True
else:
return False
list1 =["d","e","t","r","u","e"]
print("input list is :",list1)
vo=list(filter(red,list1))
print("output list is :",vo)

Comments