0% found this document useful (0 votes)
120 views

PYTHON Map, Filter and Reduce

Python functions allow you to define blocks of code that can be reused by calling the function. Functions can accept parameters and return values. Classes define custom object types with properties and methods. The built-in modules provide commonly used functions like platform that returns the system a program is running on.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views

PYTHON Map, Filter and Reduce

Python functions allow you to define blocks of code that can be reused by calling the function. Functions can accept parameters and return values. Classes define custom object types with properties and methods. The built-in modules provide commonly used functions like platform that returns the system a program is running on.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Python Functions

• function is a block of code which only runs


when it is called.
• You can pass data, known as parameters, into
a function.
• A function can return data as a result.
Creating a Function

• 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

• By default, a function must be called with the


correct number of arguments. Meaning that if
your function expects 2 arguments, you have
to call the function with 2 arguments, not
more, and not less.
def my_function(fname, lname):
  print(fname + " " + lname)
my_function("Emil", "Refsnes")
Arbitrary Arguments, *args

• If you do not know how many arguments that


will be passed into your function, add a *
before the parameter name in the function
definition.
• This way the function will receive a tuple of
arguments, and can access the items
accordingly:
example
• def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")


Default Parameter Value

• The following example shows how to use a default


parameter value.
• If we call the function without argument, it uses the
default value:
• def my_function(country = "Norway"):
  print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument

• You can send any data types of argument to a


function (string, number, list, dictionary etc.),
and it will be treated as the same data type
inside the function.
• E.g. if you send a List as an argument, it will
still be a List when it reaches the function:
• def my_function(food):
  for x in food:
    print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values

• To let a function return a value, use the return


statement:
• def my_function(x):
  return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
The pass Statement

• function definitions cannot be empty, but if


you for some reason have a function definition
with no content, put in the pass statement to
avoid getting an error.
Map, Filter and Reduce

• 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

• filter creates a list of elements for which a


function returns true.
Pgm:
number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)
# Output: [-5, -4, -3, -2, -1]
The filter resembles a for loop but it is a builtin function
and faster.
Reduce

• Reduce is a really useful function for


performing some computation on a list and
returning the result. It applies a rolling
computation to sequential pairs of values in a
list. For example, if you wanted to compute
the product of a list of integers.
Pgm
product = 1
list = [1, 2, 3, 4]
for num in list:
product = product * num
o/p:# product = 24
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
# Output: 24
Modules
• What is a Module?
• Consider a module to be the same as a code
library.
• A file containing a set of functions you want to
include in your application.
Create a Module

• To create a module just save the code you


want in a file with the file extension .py:
• Save this code in a file named mymodule.py
def greeting(name):
  print("Hello, " + name)
Use a Module

• Now we can use the module we just created,


by using the import statement
• Import the module named mymodule, and call
the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Variables in Module

• 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

• You can create an alias when you import a


module, by using the as keyword:
• import mymodule as mx
Built-in Modules

• There are several built-in modules in Python,


which you can import whenever you like.
• Import and use the platform module:
Pgm:
import platform
x = platform.system()
print(x)
O/p: windows
• globals()-function in Python returns the dictionary of current global symbol table.
• # Python3 program to demonstrate global() function
•   
• # global variable
• a=5
•   def func():
•     c = 10
•     d = c + a
•           # Calling globals()
•     globals()['a'] = d
•     print (d)
•       
• # Driver Code    
• func()
• o/p:15
• The locals() function returns a dictionary
containing the variables defined in the local
namespace
• reload() –another imported module. Actutal
module you have to reload
Python Classes

• Python is an object oriented programming


language.
• Almost everything in Python is an object, with
its properties and methods.
• To create a class, use the keyword class:
Example

• 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

• Use the __init__() function to assign values to


object properties, or other operations that are
necessary to do when the object is being
created
• All classes have a function called __init__(),
which is always executed when the class is
being initiated.
example
• class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
o/p: John 36
Object Methods

• Objects can also contain methods. Methods in


objects are functions that belong to the
object.
example
• class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
  def myfunc(self):
    print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
o/p:Hello my name is John

You might also like