PYTHON Map, Filter, Ruduce
PYTHON Map, Filter, Ruduce
# Return double of n
def addition(n):
return n + n
Output [2, 4, 6, 8]
Demonstration of map() in Python
map() with Lambda Expressions
We can also use lambda expressions with map to
achieve above result. In this example, we are using
map() with lambda expression.
numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)
print(list(result))
Output [2, 4, 6, 8]
Demonstration of map() in Python
Add Two Lists Using map and lambda
In this example, we are using map and lambda to add
two lists.
# Add two lists using map and lambda
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
Output [5, 7, 9]
Demonstration of map() in Python
Add Two Lists Using map and lambda
In this example, we are using map and lambda to add
two lists.
# Add two lists using map and lambda
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
Output [5, 7, 9]
Demonstration of map() in Python
Example : Working of map()
def calculateSquare(n):
return n*n
numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)
Output
<map object at 0x7f722da129e8>
{16, 1, 4, 9}
In the above example, each item of the tuple is squared.
filter() in python
The filter() method filters the given sequence
with the help of a function that tests each
element in the sequence to be true or not.
Python filter() Syntax
Syntax: filter(function, sequence)
• function: function that tests if each element
of a sequence is true or not.
• sequence: sequence which needs to be
filtered, it can be sets, lists, tuples, or
containers of any iterators.
filter() in python
# function that filters vowels
def fun(variable):
letters = ['a', 'e', 'i', 'o', 'u']
if (variable in letters):
return True
else:
return False
# sequence
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']
output:
The filtered letters are: e e
Filter Function in Python with Lambda
# a list contains both even and odd numbers.
seq = [0, 1, 2, 3, 5, 8, 13]
Output:
[1, 3, 5, 13]
[0, 2, 8]
reduce() in Python
# initializing list
lis = [1, 3, 5, 6, 2]
Output
The sum of the list elements is : 17
The maximum element of the list is : 6
reduce() in Python
Using Operator Functions
reduce() can also be combined with operator functions to achieve the similar functionality as with lambda functions and makes
the code more readable.