# Topic covered
* Built-in Functions
* Anonymous/lambda Functions
* map() function
* reduce() function
* filter() function
* eval() function
10.1 Anonymous/lambda Functions
Sometimes we can declare a function without any name, such type of nameless functions are called
anonymous/lambda functions
The main purpose of anonymous function is just for instant use(i.e. for one time usage)
AKA lambda functions or shorthand function
# Syntax
lambda argument_list : expression
print((lambda x: x + 1)(2)) # 3
s = lambda n:n*n
print(s(4)) # 64
s = lambda a,b:a+b
print(s(2, 3)) # 5
s = lambda a,b:a if a>b else b
print(s(10,20)) # 20
print(s(100,200)) # 200
print((lambda x, y, z=3: x + y + z)(1, 2))
Note
Lambda Function internally returns expression value and we are not required to write return statement explicitly
Sometimes we can pass function as argument to another function. In such cases lambda functions are the best choice.
We can use lambda functions very commonly with filter(), map() and reduce() functions,
because these functions expect function as argument.
10.2 map() function
map() function returns a map object(which is an iterator) of the results after applying
the given function to each item of a given iterable (list, tuple etc.)
# str to int
num = ['1', '2', '3']
res = list(map(int, num))
print(res)
# Square
def square(number):
return number ** 2
numbers = [1, 2, 3, 4, 5]
print(list(map(square, numbers)))
# Square using map and lambda
print(list(map(lambda x:x*x, numbers)))
first_it = [1, 2, 3]
second_it = [4, 5, 6, 7]
print(list(map(pow, first_it, second_it)))
# x- y
print(list(map(lambda x, y: x - y, [2, 4, 6], [1, 3, 5])))
# [1, 1, 1]
print(list(map(lambda x, y, z: x + y + z, [2, 4], [1, 3], [7, 8])))
# [10, 15]
# Eg 5
string_it = ["processing", "strings", "with", "map"]
print(list(map(str.upper, string_it)))
# ['PROCESSING', 'STRINGS', 'WITH', 'MAP']
with_spaces = ["processing ", " strings", "with ", " map "]
print(list(map(str.strip, with_spaces)))
# ['processing', 'strings', 'with', 'map']
with_dots = ["processing..", "...strings", "with....", "..map.."]
print(list(map(lambda s: s.strip("."), with_dots)))
# ['processing', 'strings', 'with', 'map']
# Eg 6
import re
def remove_punctuation(word):
return re.sub(r'[!?.:;,"()-]', "", word)
text = """Some people, when ,,confronted... with a problem, think"""
words = text.split()
print(list(map(remove_punctuation, words)))
10.3 reduce() function
reduce() function reduces sequence of elements into a single element by applying the specified function.
reduce() function present in functools module and hence we should write import statement.
reduce(function, sequence)
from functools import *
l = [10,20,30,40,50]
result=reduce(lambda x,y:x+y,l)
print(result) # 150
l = [1,2,3,4,5,4]
# Does not work on 3 variable
reduce(lambda x , y , z : x+y+z , l) # TypeError
reduce(lambda x , y : x+y , [1])
# 1
# Biggest emement in list
reduce(lambda x,y : x if x> y else y , l)
# 5
10.4 filter() function
We can use filter() function to filter values from the given sequence based on some condition.
filter(function, sequence) -
where function argument is responsible to perform conditional check
sequence can be list or tuple or string.
# Working of filter()
def check_even(number):
if number % 2 == 0:
return True
return False
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list(filter(check_even, numbers))
# Output: [2, 4, 6, 8, 10]
# Using Lambda Function Inside filter()
list(filter(lambda x: (x%2 == 0), numbers))
list(filter(lambda x: True if x%2==0 else False, numbers))
# [2, 4, 6, 8, 10]
l2 = ["sudh" , "pwskills" , "kumar" , "bengalore" , "krish"]
print(list(filter(lambda x : len(x) < 6 , l2)))
10.5 eval() function
- The eval function evaluates the String like a
python expressionand returns the result as an integer. eval(expression, globals=None, locals=None)- The globals must be represented as a dictionary and the locals as a mapped object.
x = 1
print(eval('x + 1'))
print(eval("1024 + 1024"))
code = compile("5 + 4", "<string>", "eval")
print(eval(code))
print()
x = 100
print(eval("x + 10", {"x": x}))
print(eval("x + y", {"x": x, "y": x}))