Monday, 4 June 2018

Python lambda expression

The lambda expression are used to create small anonymous one-line functions. They are basically created at run-time and are not bound to the name of the functions. So they are also called throw-away functions.i.e they are just needed where they have been created.They return definition of the function on the fly. Lambda functions don't have  a return statement , they always return an expression.
They are mostly use along with another function or inside a function definition.
Syntax :

lambda [arg1 [,arg2,.....argn]]:expression 
The lambda operator is mostly used in combination with functions map, filter and reduce. We can put a lambda definition anywhere a function is expected.

For example :
1. use with filter() function

multiple_3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])
This function returns array of multiples of 3. Lambda expression has filtered out all the elements that are divisible by 3 from the given array. 

2. use with sorted()  function 

>>> sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(5-x))
[5, 4, 6, 3, 7, 2, 8, 1, 9]
3. Defining with in another function

def make_incrementor(n):
  return lambda x: x + n
f = make_incrementor(42)
f(0)
>>> 42
f(1)
>>> 43

4. Use with reduce() function 
>>> reduce(lambda a,b: '{}',"{}".format(a,b),[1,2,3,4,5,6,7,8,9])
'1,2,3,4,5,6,7,8,'
5. Making a flatten list out of list of lists 

l = [[1,2,3],[4,5,6],[7,8,9]]
flatten = lambda l: [item for sublist in l for item in sublist]
print flatten(l)
will give output :
[1,2,3,4,5,6,7,8,9]

No comments:

Post a Comment

Loan Prediction Analysis

In this post I will share my visuals ,learning and understanding of a dataset and using various algorithms of Machine Learning to analyse i...