What is this lambda function?Lambda function - is a small anonymous function which can operate with the little part of data. An anonymous function is a simple version of the standard function, and if the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. The main advantage of anonymous functions is absence of necessity to define the function. Let see little example of Lambda function.
Is nearly the same as
>>> double = lambda x: x * 2 >>> double(2) 4
From this simple example, you see how looking is Lambda functions. It's pretty much easier than simple function and can be used anywhere where we want. But reasons question will be "Why I should use it? What is an advantage, in one line?"
>>> def double(x): ... return x*2 ... >>> double(2) 4
My answer no. The advantage of the lambda operator can be seen when it is used in combination with other functions like "filter", "map" or "reduce".
Filter and Lambda functionsFilter - is a function which is working with arrays and filtering them due to some conditions. This function is calling like
filter(function, iterable)where iterable will be our array and function will be our Lambda function. For example :
From this, we see how to easy array can be filtered by even and odd numbers.
>>> full_list = [1, 2, 3, 4, 5] >>> new_list = list(filter(lambda x: (x%2 == 0) , full_list)) >>> print new_list [2, 4]
Map and Lambda functionsMap - function, is function which is applying some changes on input list. For example, there is function which is multiply each element on 2
And there is faster and simpler way to do the same actions
>>> items = [1, 2, 3, 4, 5] >>> squared =  >>> for i in items: ... squared.append(i*2) ... >>> print(squared) [2, 4, 6, 8, 10]
>>> squared = list(map(lambda x: x*2, items)) >>> print(squared) [2, 4, 6, 8, 10]
Reduce and Lambda functionsReduce - function for performing some computation on a list and returning the result. Let's imagine that we wanted to compute a list of integers. And of course, to make some actions with each element, we need to use the cycle
Now let’s try it with reduce:
>>> value = 0 >>> list = [1, 2, 3, 4, 5] >>> for i in list: ... value += i ... >>> print(value) 15
>>> value = reduce((lambda x, y: x + y), [1, 2, 3, 4, 5]) >>> print(value) 15