Lambda and Sorted With Key - Vha
Lambda and Sorted With Key - Vha
2 syntax:
[2]: 7
1
lambda has no return value(infact,returns a function)
lambda is written in 1 line
not reusable
[3]: True
even
[8]: 7
[9]: 35
114
10
40
27
40
14
2
10 higher order function
A function is called Higher Order Function if it contains other functions as a parameter or returns
a function as an output i.e, the functions that operate with another function are known as Higher
order Functions. It is worth knowing that this higher order function is applicable for functions and
methods as well that takes functions as a parameter or returns a function as a result. Python too
supports the concepts of higher order functions.
Properties of higher-order functions:
A function is an instance of the Object type.
You can store the function in a variable.
You can pass the function as a parameter to another function.
You can return the function from a function.
You can store them in data structures such as hash tables, lists,
[12]: # Example
def square(x):
return x**2
def cube(x):
return x**3
# HOF
def transform(f,L):
output = []
for i in L:
output.append(f(i))
print(output)
L = [1,2,3,4,5]
transform(square,L)
[13]: L = [1,2,3,4,5]
transform(cube,L)
3
y=y(3)
return x+y
higher_ord_fun(20,lambda x:x*x)
[18]: 29
11 map
12 filter
13 reduce
[19]: list1=[10,40,56,27,13,15,70]
divide=list(filter(lambda x: (x%4==0),list1))
print(divide)
[40, 56]
list(filter(lambda x:x>5,L))
[20]: [6, 7]
list(filter(lambda x:x.startswith('a'),fruits))
[21]: ['apple']
[22]: list2=[10,40,56,27,13,15,70]
double=list(map(lambda x:x*2,list2))
print(double)
[23]: list3=[2,5,10,6,4]
cube=list(map(lambda x:x**3,list3))
print(cube)
4
[24]: ['odd', 'even', 'odd', 'even', 'odd']
4800
10
users = [
{
'name':'Rahul',
'age':45,
'gender':'male'
},
{
'name':'Nitish',
'age':33,
'gender':'male'
},
{
'name':'Ankita',
'age':50,
'gender':'female'
}
]
list(map(lambda users:users['gender'],users))
functools.reduce(lambda x,y:x+y,[1,2,3,4,5])
[28]: 15
5
[29]: 45
[30]: l1=[1,2,3,4,5,6]
print(sorted(l1))
t1=(1,2,3,4,5,6)
print(sorted(t1))
d1={1:'a',2:'c',3:"b"}
print(sorted(d1.items()))
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[(1, 'a'), (2, 'c'), (3, 'b')]
[31]: d1={1:'a',2:'c',3:"b"}
print(sorted(d1.items(),key=lambda x:x[1]))
print(d1.items())
[32]: t=[(1,15),(2,11),(3,17),(4,12)]
def second(z):
return z[1]
print(sorted(t,key=second))
[33]: t=[(1,15),(2,11),(3,17),(4,12)]
d=dict(t)
print(d)
print(sorted(d.items(),key=lambda x:x[1]))
print(d.items())
[34]: t=[(1,15),(2,11),(3,17),(4,12)]
print(sorted(t,key=lambda x:x[1]))
[40]: t=["vishal","vishal10","vishal9"]
print(sorted(t,key=len,reverse=True))
6
['vishal10', 'vishal9', 'vishal']
[41]: t=["vishal","vishal10","vishal9"]
print(sorted(t,key=len))
[ ]: