Day 30 - Learn the concept of comprehension,lambda,map,filter,reduce via simple examples
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 8 11:20:22 2020
@author: Rakesh.Ranjan
"""
def square(x):
return x**2
def even(x):
return x%2 == 0
numbers = [1,2,3,4]
#Comprehension
#1. the expression inside the brackets first starts with the operation/output that you desire, and then loops and conditionals occur in the same order of the regular code.
lc_square = [numbers[i]**2 for i in range(len(numbers))]
print('Comprehension example:',lc_square)
#lambda
#lambda input parameter(s):operation/output
countries = ['India','Pakistan','Bhutan','Nepal','Bangladesh']
func_lambda = lambda x: x.lower()
print('lambda example:',func_lambda('India'))
#A. Map
#map(function,iterable object)
#1. The function here can be a lambda function or a function object.
#2. The iterable object can be a string, list, tuple, set or dictionary.
lm_map = map(square, numbers)
print('map example:',list(lm_map))
#B. Filter
#filter(function,iterable object)
#1. The function object passed to the filter function should always return a boolean value.
#2. The iterable object can be a string, list, tuple, set or dictionary.
divby2 = lambda x : x % 2 == 0
even_filter = filter(divby2, numbers)
even_map = map(even, numbers)
print('map example:',list(even_map),' filer example:', list(even_filter))
#C. Reduce
#reduce(function,iterable object)
#1. The function object passed to the reduce function decides what expression is passed to the iterable object.
#2. The iterable object can be a string, list, tuple, set or dictionary.
#3. Also, reduce function produces a single output.
from functools import reduce
fact = lambda x,y : x * y
lf_filter = reduce(fact,numbers)
print('Reduce example:',lf_filter)
Output:
#RR #Day30 #Python #Function #comprehension #lambda #map #filter #reduce #HappyLearning #WeLearnEveryday
Comments
Post a Comment