PYTHON Map, Filter and Reduce
PYTHON Map, Filter and Reduce
• def my_function():
print("Hello from a function")
• Calling a Function
• To call a function, use the function name
followed by parenthesis:
• def my_function():
print("Hello from a function")
my_function()
Arguments
• Information can be passed into functions as
arguments.
• Arguments are specified after the function name,
inside the parentheses. You can add as many
arguments as you want, just separate them with a
comma.
• The following example has a function with one
argument (fname). When the function is called, we
pass along a first name, which is used inside the
function to print the full name:
example
• def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Number of Arguments
• Map
Map applies a function to all the items in an
input_list.
Syntax
map(function_to_apply, list_of_inputs)
Program
def multiply(x):
return (x*x)
def add(x):
return (x+x) funcs = [multiply, add]
for i in range(5):
value = list(map(lambda x: x(i), funcs))
print(value)
# Output
• : # [0, 0]
• # [1, 2]
• # [4, 4]
• # [9, 6]
• # [16, 8]
Filter
• The module can contain functions, as already described, but also variables
of all types (arrays, dictionaries, objects etc)
• Save this code in the file mymodule.py
• person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
• Import the module named mymodule, and access the person1 dictionary
import mymodule
a = mymodule.person1["age"]
print(a)
Output: 36
Re-naming a Module
• class MyClass:
x=5
Create Object
• Example
• Create an object named p1, and print the
value of x:
• p1 = MyClass()
print(p1.x)
o/p:5
The __init__() Function