map_reduce_filter_lambda_generator
map_reduce_filter_lambda_generator
Lambda, Generator
Lambda Function or Anonymous Function
● Function that is created using lambda keyword not using def keyword.
● Lambda function are just needed where they have been created and
can be used anywhere a function required.
● Lambda function contains only a single line .
fib(10)
• Sometimes we want to pass an entire
function as a parameter
• Python has functions as first-class citizens,
so you can do this
• You simply pass the functions by name
Higher-Order Functions
1 nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6, 8, 0, 3]
2
3 nums = list(map(lambda x : x % 5, nums))
4
5
print(nums)
6
7 #[0, 4, 2, 2, 1, 0, 4, 3, 0, 1, 3, 0, 3]
Example
items = [ “copper”, “Zinc”, “Nickel”]
items_new = list(map(str.upper, items))
print(items_new)
OUTPUT
Loop Method:
- distance(x, y, z) = sqrt(x**2 + y**2 + z**2)
- loop through the list and add results to a new list
Solution
1 from math import sqrt
2
3 points = [(2, 1, 3), (5, 7, -3), (2, 4, 0), (9, 6, 8)]
4
5 def distance(point) :
6 x, y, z = point
7 return sqrt(x**2 + y**2 + z**2)
8
9 distances = list(map(distance, points))
Filter iterable)
filter(function,
• The filter runs through each element of iterable (any
iterable object such as a List or another collection)
• It applies function to each element of iterable
• If function returns True for that element then the
element is put into a List
• This list is returned from filter in versions of python under
3
• In python 3, filter returns an iterator which must be cast
to type list with list()
Filter Example
Example
1 nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6, 8, 0, 3]
2
3 nums = list(filter(lambda x : x != 0, nums))
4
5 print(nums) #[4, 7, 2, 1, 9, 3, 5, 6, 8, 3]
6
Example - to find Palindromes in a list of strings
palindrome_list = [“Top”, “nun”, “tattarrattat”, “advice”, “noon”]
print(palindrome_list)
print(result)
Ex: to generate Even numbers
def even(n):
if(n % 2 == 0)
return TRUE
else:
return FALSE
lst = [2,10,14,9,50]
Example
1 nums = [1, 2, 3, 4, 5]
2
3 sum = reduce(lambda x, y : x+y, nums,10)
4
5 Print(sum)
6
7 >> 25
Reduce Example
Example
Solution
1 nums = [92, 27, 63, 43, 88, 8, 38, 91, 47, 74, 18, 16,
29, 21, 60, 27, 62, 59, 86, 56]
2
3 sum = reduce(lambda x, y : x + y, nums) / len(nums)
4
MapReduce