Python is a simple, easy to use yet powerful language. Python includes an infinite number of built-in functions. Here we will discuss some of the beautiful things of the python.
Lambda: Lambda is an anonymous function. Anonymous functions in python mean that these functions don’t have a name and we write them as one-liners. Normal functions in python start with a def keyword and have a function name. In other words, anonymous does not start with def and does not have any function name. Lambda is one such type of function. Lambda function has one expression and can take any type of argument.
lambda arguments: expression
#Normal Python function def add(a, b): return a+ b x = add(2,3) print(x) Output = 5 #Lambda Function x = lambda a, b : a +b print(x(5,6)) #Output = 11 x = lambda a, b, c : a + b + c print(x(5,2,3)) #Output = 10
Map: Map is a Python built-in function that is used to iterate an iterable through a specified function. It executes the function through each item in the iterable. It is used to apply a function to a sequence of elements like a list or dictionary.
def sum(a,b): return a+b x = map(sum,[1,2,3],[1,2,3]) print(x) #Output = [2,4,6] def length(a): return len(a) x = map(length, ("apple","orange","banana")) print(x) #Output = [5,6,6]
Filter: Filter is similar to the map but it only returns those values for which the applied function returns True. The function returns an iterator where the items are filtered through a function to test if the item is accepted or not.
num = [5,8,9,11,15,13,21,119,120] def filter_fun(x): if x < 100: return False else: return True x = filter(filter_fun, num) for a in x: print(a) #Output : 119 120
now. Read More