UNIT – III
ADVANCED FUNCTIONS, ARRAYS
Fruitful functions: return values, parameters, local and global scope, function
composition, recursion; Advanced Functions: lambda, map, filter, reduce, basic data
type comprehensions. Python arrays: create an array, Access the Elements of an Array,
array methods.
Functions, Arrays:
Fruitful functions:
We write functions that return values, which we will call fruitful functions. We have
seen the return statement before, but in a fruitful function the return statement includes
a return value. This statement means: "Return immediately from this function and use
the following expression as a return value."
(or)
Any function that returns a value is called Fruitful function. A Function that does not
return a value is called a void function
Return values:
The Keyword return is used to return back the value to the called function.
# returns the area of a circle with the given radius:
def area(radius):
temp = 3.14 * radius**2
return temp
print(area(4))
(or)
def area(radius):
return 3.14 * radius**2
print(area(2))
Sometimes it is useful to have multiple return statements, one in each branch of a
conditional:
def absolute_value(x):
if x < 0:
return -x
else:
return x
Since these return statements are in an alternative conditional, only one will be
executed.
1
As soon as a return statement executes, the function terminates without executing any
subsequent statements. Code that appears after a return statement, or any other place
the flow of execution can never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path through the
program hits a return statement. For example:
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x
This function is incorrect because if x happens to be 0, both conditions is true, and the
function ends without hitting a return statement. If the flow of execution gets to the end
of a function, the return value is None, which is not the absolute value of 0.
>>> print absolute_value(0)
None
By the way, Python provides a built-in function called abs that computes absolute
values.
# Write a Python function that takes two lists and returns True if they have at
least one common member.
def common_data(list1, list2):
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [1,2,3,4,5]))
print(common_data([1,2,3,4,5], [1,7,8,9,510]))
print(common_data([1,2,3,4,5], [6,7,8,9,10]))
Output:
C:\Users\\AppData\Local\Programs\Python\Python38-32\pyyy\fu1.py
True
True
2
None
#
def area(radius):
b = 3.14159 * radius**2
return b
Parameters:
Parameters are passed during the definition of function while Arguments are passed
during the function call.
Example:
#here a and b are parameters
def add(a,b): #//function definition
return a+b
#12 and 13 are arguments
#function call
result=add(12,13)
print(result)
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/paraarg.py
25
Some examples on functions:
# To display vandemataram by using function use no args no return type
#function defination
def display():
print("i am in main")
#function call
display()
print("i am in main")
3
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
i am in main
vandemataram
i am in main
#Type1 : No parameters and no return type
def Fun1() :
print("function 1")
Fun1()
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
function 1
#Type 2: with param without return type
def fun2(a) :
print(a)
fun2("hello")
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Hello
#Type 3: without param with return type
def fun3():
return “Welcome to Python”
print (fun3())
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Welcome to python
#Type 4: with param with return type
def fun4(a):
return a
print(fun4("python is better then c"))
4
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
python is better then c
Local and Global scope:
Local Scope:
A variable which is defined inside a function is local to that function. It is accessible
from the point at which it is defined until the end of the function, and exists for as long
as the function is executing
Global Scope:
A variable which is defined in the main body of a file is called a global variable. It will
be visible throughout the file, and also inside any file which imports that file.
• The variable defined inside a function can also be made global by using the
global statement.
def function_name(args):
global x # declare global variable inside a function
# Create a global variable
x = "global"
def f():
print("x inside :", x)
f()
print("x outside:", x)
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
x inside : global
x outside: global
# Create a local variable
def f1():
y = "local"
print(y)
f1()
5
Output:
local
• If we try to access the local variable outside the scope for example,
def f2():
y = "local"
f2()
print(y)
Then when we try to run it shows an error,
Traceback (most recent call last):
File " C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
", line 5, in <module>
print(y)
NameError: name 'y' is not defined
The output shows an error, because we are trying to access a local variable y in a
global scope whereas the local variable only works inside f2() or local scope.
# Use local and global variables in same code
x = "global"
def f3():
global x
y = "local"
x=x*2
print(x)
print(y)
f3()
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
globalglobal
local
• In the above code, we declare x as a global and y as a local variable in the f3().
Then, we use multiplication operator * to modify the global variable x and
we print both x and y.
• After calling the f3(), the value of x becomes global global because we used the
x * 2 to print two times global. After that, we print the value of local variable y
i.e local.
6
# Use Global variable and Local variable with same name
x=5
def f4():
x = 10
print("local x:", x)
f4()
print("global x:", x)
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
local x: 10
global x: 5
Function Composition:
Having two (or more) functions where the output of one function is the input for
another. So for example if you have two functions FunctionA and FunctionB you
compose them by doing the following.
FunctionB(FunctionA(x))
Here x is the input for FunctionA and the result of that is the input for FunctionB.
Example 1:
#Create a function compose2
>>> def compose2(f, g):
return lambda x:f(g(x))
>>> def d(x):
return x*2
>>> def e(x):
return x+1
>>>a(5) #FunctionC(x)
>>>a= compose2(d,e) # FunctionC = compose(FunctionB,FunctionA)
12
In the above program we tried to compose n functions with the main function created.
7
Example 2:
>>> colors=('red','green','blue')
>>> fruits=['orange','banana','cherry']
>>> zip(colors,fruits)
<zip object at 0x03DAC6C8>
>>> list(zip(colors,fruits))
[('red', 'orange'), ('green', 'banana'), ('blue', 'cherry')]
Recursion:
Recursion is the process of defining something in terms of itself.
Python Recursive Function
We know that in Python, a function can call other functions. It is even possible for the
function to call itself. These types of constructs are termed as recursive functions.
Factorial of a number is the product of all the integers from 1 to that number. For
example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Following is an example of recursive function to find the factorial of an integer.
# Write a program to factorial using recursion
def fact(x):
if x==0:
result = 1
else :
result = x * fact(x-1)
return result
print("zero factorial", fact(0))
print("five factorial", fact(5))
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/rec.py
zero factorial 1
five factorial 120
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
8
return (x * calc_factorial(x-1))
num = 4
print("The factorial of", num, "is", calc_factorial(num))
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/rec.py
The factorial of 4 is 24
Python arrays:
Array is a container which can hold a fix number of items and these items should be of
the same type. Most of the data structures make use of arrays to implement their
algorithms. Following are the important terms to understand the concept of Array.
• Element− Each item stored in an array is called an element.
• Index − Each location of an element in an array has a numerical index, which is
used to identify the element.
Array Representation
Arrays can be declared in various ways in different languages. Below is an
illustration.
Elements
Int array [10] = {10, 20, 30, 40, 50, 60, 70, 80, 85, 90}
Type Name Size Index 0
As per the above illustration, following are the important points to be considered.
• Index starts with 0.
• Array length is 10 which means it can store 10 elements.
• Each element can be accessed via its index. For example, we can fetch an
element at index 6 as 70
Basic Operations
Following are the basic operations supported by an array.
• Traverse − print all the array elements one by one.
• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given index or by the value.
• Update − Updates an element at the given index.
9
Array is created in Python by importing array module to the python program. Then the
array is declared as shown below.
from array import * array
Name=array(typecode, [initializers])
Typecode are the codes that are used to define the type of value the array will hold.
Some common typecodes used are:
Typecode Value
b Represents signed integer of size 1 byte/td>
B Represents unsigned integer of size 1 byte
c Represents character of size 1 byte
i Represents signed integer of size 2 bytes
I Represents unsigned integer of size 2 bytes
f Represents floating point of size 4 bytes
d Represents floating point of size 8 bytes
Creating an array:
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
Output:
>>>
RESTART: C:/Users//AppData/Local/Programs/Python/Python38-32/arr.py
10
20
30
40
50
Access the elements of an Array:
10
Accessing Array Element
We can access each element of an array using the index of the element.
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])
Output:
RESTART: C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/arr2.py
10
30
Array methods:
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Note: Python does not have built-in support for Arrays, but Python Lists can be used
instead.
Example:
>>> college=[" ","it","cse"]
>>> college.append("autonomous")
>>> college
[' ', 'it', 'cse', 'autonomous']
11
>>> college.append("eee")
>>> college.append("ece")
>>> college
[' ', 'it', 'cse', 'autonomous', 'eee', 'ece']
>>> college.pop()
'ece'
>>> college
[' ', 'it', 'cse', 'autonomous', 'eee']
>>> college.pop(4)
'eee'
>>> college
[' ', 'it', 'cse', 'autonomous']
>>> college.remove("it")
>>> college
12