Lambda Functions¶
Let us recap details related to lambda functions.
We can develop functions with out names. They are called Lambda Functions and also known as Anonymous Functions.
They are quite extensively used as part of functions such as map, reduce, sort, sorted etc.
We typically use them to pass as arguments to higher order functions which takes functions as arguments
Tasks¶
Let us perform few tasks related to lambda functions.
Create a generic function mySum which is supposed to perform arithmetic using integers within a range.
It takes 3 arguments -
lb
,ub
andf
.Function f should be invoked inside the function on each element within the range.
def mySum(lb, ub, f):
total = 0
for e in range(lb, ub + 1):
total += f(e)
return total
Sum of integers between lower bound and upper bound using
mySum
.
def get_i(i):
return i
mySum(2, 4, lambda i: i)
9
mySum(2, 4, get_i)
9
Sum of squares of integers between lower bound and upper bound using
mySum
.
mySum(2, 4, lambda i: i * i)
29
def sqr(i): return i * i
mySum(2, 4, sqr)
29
Sum of the even numbers between lower bound and upper bound using
mySum
.
mySum(2, 4, lambda i: i if i%2 == 0 else 0)
6
def even(i): return i if i % 2 == 0 else 0
mySum(2, 4, even)
6
Sort the list of tuples in descending order by 2nd elements with in the tuples
salaries = [
(1, 1000.0),
(2, 1800.0),
(3, 1500.0),
(4, 750.0)
]
type(salaries)
list
type(salaries[0])
tuple
sorted?
Signature: sorted(iterable, /, *, key=None, reverse=False)
Docstring:
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
Type: builtin_function_or_method
sorted(salaries)
[(1, 1000.0), (2, 1800.0), (3, 1500.0), (4, 750.0)]
sorted(salaries, reverse=True)
[(4, 750.0), (3, 1500.0), (2, 1800.0), (1, 1000.0)]
t = (1, 1000.0)
type(t)
tuple
t[1]
1000.0
sorted(salaries, key=lambda sal: sal[1])
[(2, 1800.0), (3, 1500.0), (1, 1000.0), (4, 750.0)]
sorted(salaries, key=lambda sal: sal[1], reverse=True)
[(2, 1800.0), (3, 1500.0), (1, 1000.0), (4, 750.0)]
for sal in sorted(salaries, key=lambda sal: sal[1], reverse=True):
print(sal)
(2, 1800.0)
(3, 1500.0)
(1, 1000.0)
(4, 750.0)