LAMBDA
Lambda is an anonymous functions which will mainly help you in writing other single line functions. It’s very powerful tool, and if you are able to harness it’s power you can do things that other can’t.
Let me give you a brief idea about it.
>>> a = lambda x, y: (x+y)*y -(x+y)
>>> a(1, 2)
3
As i said Lambda is an anonymous function that helps to create other functions, Here a is a function defined and x, y are the two parameters passed into it. It does a complicated mathematical calculation and returns the value. I can then execute a which is a variable holding the function object and pass two variables 1, 2 into it and it’s gives me the necessary result.
Let’s give you another example.
>> def generic_function(x):
. . . : return lambda y: do_operation(y, x)
>>> def do_operation(a, b):
. . . : return a + b
>>> a = generic_function(1)
>>> a(2)
3
Explanation:
i. generic_function passes variable x, y into do_operation method. x is variable of generic_function and y is variable of lambda that is supplied through the object of generic_function.
ii. a is the object of generic function that holds the functions and passes variable y into generic_function.
iii. lambda is used to evaluate both variables and executes do_operation on them, which sums up both the numbers and gives result.
COMPREHENSIONS
There is another way to write awesome code in pure pythonic way, Comprehensions.
Two types of comprehensions are there in python i. List Comprehensions, ii. Dictionary Comprehensions.
i. List Comprehensions:
>>> a = [1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10]
>>> b = [i for i in a]
>>> b
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10]
>>> c = [i for i in a if i %2 == 0]
>>> c
[2, 4, 6, 8, 10]
>>> d = [i**2 for i in a if i%2 != 0]
>>> d
[1, 9, 25, 25, 49, 81]
I am doing a lot of stuffs in just one line. a is a dummy list that i have defined. b is a copy of list a but in a new variable. c is all the even numbers out of the previous list and d is the square of all odd numbers from the same list. As you can see you can have loops conditions and extra operations just in one line of code and build powerful functionalities from them.
ii. Dictionary Comprehentions
>> a = [1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10]
>>> b = {i:i**2 for i in a}
>>> b
{1:1, 2:4, 3:9, 4:16, 5:25, 5:25, 6:36, 7:49, 8:64, 9:81, 10:100}
what have i done here ? i have just created a dictionary where key is the element from the list a and value is the square of each element.
You can try the same thing with tuples also but it will end up creating a generator object out of it. To create a tuple simply create a tuple simple create a list and typecast it into tuple.
That’s all i have for now I will comeback soon with some more tricks in python using map, reduce, lambda, filter and comprehensions. bye bye.