I\'m reading through the Python documentation to really get in depth with the Python language and came across the filter and map functions. I have used filter before, but never
Filter function is used to filter results from our original list whereas Map function is used to apply some function on our original list and a new list is hence generated. See below examples where filter function is used to return items in list only when they are odd. Map function is used in below to return square of each item in list.
Lambda function: Using Lambda : Lambda definition does not include a “return” statement, it always contains an expression which is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions.
g = lambda x: x*x*x
print(g(5))
#125
The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True. Here is a small program that returns the odd numbers from an input list:
li = [4,5,7,8,9]
final_list = list(filter(lambda x: (x%2 != 0) , li))
print(final_list)
#[5,7,9]
The map() function in Python takes in a function and a list as argument. A new list is returned by applying function to each item of list.
li = [5, 7, 4, 9]
final_list = list(map(lambda x: x*x , li))
print(final_list)
#[25, 49, 16, 81]