In Python, anonymous function means that a function is without a name.
In Python def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions having following syntax:
lambda arguments: expression
This function can have any number of arguments but only one expression, which is evaluated and returned.
One is free to use lambda functions wherever function objects are required.
You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.
It has various uses in particular fields of programming besides other types of expressions in functions.
Let’s look at this example and try to understand the difference between a normal def defined function and lambda function. This is a program that returns the cube of a given value:
# Python code to illustrate cube of a number
# showing difference between def() and lambda().
def cube(y):
return y*y*y;
g = lambda x: x*x*x
print(g(7))
print(cube(5))
Output:
343
125
Without using Lambda : Here, both of them returns the cube of a given number. But, while using def, we needed to define a function with a name cube and needed to pass a value to it. After execution, we also needed to return the result from where the function was called using the return keyword.
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.
Lambda functions can be used along with built-in functions like filter(), map() and reduce().
Use of lambda() with filter()
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:
# Example of python code to illustrate
# filter() with lambda()
list_math = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(filter(lambda x: (x%2 != 0) , list_math))
print(final_list)
Output:
[5, 7, 97, 77, 23, 73, 61]
Use of lambda() with map()
The map() function in Python takes in a function and a list as argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item. Example:
# Python code to illustrate
# map() with lambda()
# to get double of a list.
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(map(lambda x: x*2 , li))
print(final_list)
Output:
[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
Use of lambda() with reduce()
The reduce() function in Python takes in a function and a list as argument. The function is called with a lambda function and a list and a new reduced result is returned. This performs a repetitive operation over the pairs of the list. This is a part of functools module. Example:
# Python code to illustrate
# reduce() with lambda()
# to get sum of a list
from functools import reduce
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
print (sum)
Output:
193
Here the results of previous two elements are added to the next element and this goes on till the end of the list like (((((5+8)+10)+20)+50)+100).
In Python def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions having following syntax:
lambda arguments: expression
This function can have any number of arguments but only one expression, which is evaluated and returned.
One is free to use lambda functions wherever function objects are required.
You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.
It has various uses in particular fields of programming besides other types of expressions in functions.
Let’s look at this example and try to understand the difference between a normal def defined function and lambda function. This is a program that returns the cube of a given value:
# Python code to illustrate cube of a number
# showing difference between def() and lambda().
def cube(y):
return y*y*y;
g = lambda x: x*x*x
print(g(7))
print(cube(5))
Output:
343
125
Without using Lambda : Here, both of them returns the cube of a given number. But, while using def, we needed to define a function with a name cube and needed to pass a value to it. After execution, we also needed to return the result from where the function was called using the return keyword.
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.
Lambda functions can be used along with built-in functions like filter(), map() and reduce().
Use of lambda() with filter()
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:
# Example of python code to illustrate
# filter() with lambda()
list_math = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(filter(lambda x: (x%2 != 0) , list_math))
print(final_list)
Output:
[5, 7, 97, 77, 23, 73, 61]
Use of lambda() with map()
The map() function in Python takes in a function and a list as argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item. Example:
# Python code to illustrate
# map() with lambda()
# to get double of a list.
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(map(lambda x: x*2 , li))
print(final_list)
Output:
[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
Use of lambda() with reduce()
The reduce() function in Python takes in a function and a list as argument. The function is called with a lambda function and a list and a new reduced result is returned. This performs a repetitive operation over the pairs of the list. This is a part of functools module. Example:
# Python code to illustrate
# reduce() with lambda()
# to get sum of a list
from functools import reduce
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
print (sum)
Output:
193
Here the results of previous two elements are added to the next element and this goes on till the end of the list like (((((5+8)+10)+20)+50)+100).
Map Function
map() is a function
that takes in two arguments: a function and a sequence iterable. In the form:
map(function, sequence)
The first argument is
the name of a function and the second a sequence (e.g. a list). map() applies
the function to all the elements of the sequence. It returns a new list with
the elements changed by function.
It is very similar to
list comprehension.
mi_players = ["Rohit Sharma", "Jasprit
Bumrah", "Siddhesh Lad", "Ishan Kishan", "Hardik
Pandya"]
Lambda functions independently are not used many a times but they are
quite often used along with map, reduce and filter.
Lets use map function to get the first names of mi_players
list(map(lambda x :
x.split()[0],mi_players))
['Rohit', 'Jasprit', 'Siddhesh',
'Ishan', 'Hardik']
Given the runs
scored by players in 3 matches.
Find the sum of runs scored by each player.
Find the sum of runs scored by each player.
match1 = [19,28,56,89]
match2 = [53,45,76,92]
match3 = [91,100,6,12]
# Sum of runs scored by each player
using map()
list(map(lambda x,y,z:x+y+z, match1,
match2, match3))
[163, 173, 138, 193]
Reduce Function
This is a bit tough part to understand. The function reduce(function, sequence) continually applies the function to the sequence. It then returns a single value.
If seq = [ s1, s2, s3, ... , sn ], calling reduce(function, sequence) works like this:
At first the first two elements of seq will be applied to function, i.e. func(s1,s2)
The list on which reduce() works looks now like this: [ function(s1, s2), s3, ... , sn ]
In the next step the function will be applied on the previous result and the third element of the list, i.e. function(function(s1, s2),s3)
The list looks like this now: [ function(function(s1, s2),s3), ... , sn ]
It continues like this until just one element is left and return this element as the result of reduce()
Using reduce() find the maximum of the below list
l = [4,2,3,1]
# import reduce
from functools import reduce
#Find the maximum of a sequence (This already exists as max())
find_max = lambda a,b: a if (a > b) else b
#Find max
reduce(find_max,l)
4
Filter Function
The function filter(function,
sequence) offers a convenient way to filter out all the elements of an
iterable, for which the function returns True.
The function filter(function,sequence) needs a function as its
first argument. The function needs to return a boolean value (either True or
False). This function will be applied to every element of the iterable. Only if
the function returns True will the element of the iterable be included in the
result.
Given the list l, print all the even
numbers in the list.
l = [3,2,1,5,7,12,14,13]
list(filter(lambda x: x%2==0,l))
[2, 12, 14]
Zip Function
zip() makes an iterator that aggregates elements from each of the iterables.
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.
zip() is equivalent to:
```python
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield tuple(result)
```
zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables.
list(zip('ABCD', 'xy'))
[('A', 'x'), ('B', 'y')]
In the above example, length of 'ABCD' is not same 'xy', that is why only first two characters of the 2 strings were zipped together.
Using zip function create a list names with first name and last name of each player
first_names = ['Rohit', 'Jasprit', 'Siddhesh', 'Ishan', 'Hardik']
last_names = ['Sharma', 'Bumrah', 'Lad', 'Kishan', 'Pandya']
list(zip(first_names,last_names))
[('Rohit', 'Sharma'),
('Jasprit', 'Bumrah'),
('Siddhesh', 'Lad'),
('Ishan', 'Kishan'),
('Hardik', 'Pandya')]
for i,j in list(zip(first_names,last_names)):
print(i+" "+j)
Rohit Sharma
Jasprit Bumrah
Siddhesh Lad
Ishan Kishan
Hardik Pandya
Unzip a list into tuple
Using list comprehension is the most naive approach to perform this task of unzipping and usually not used to perform this task, but good method to start with.
test_list = [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]
print ("Original list is : " + str(test_list))
res = [[ i for i, j in test_list ], [ j for i, j in test_list ]]
# Printing modified list
print ("Modified list is : " + str(res))
Output :
Original list is : [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]
Modified list is : [['Akshat', 'Bro', 'is', 'Placed'], [1, 2, 3, 4]]
No comments:
Post a Comment