Unit III Python
Unit III Python
These functions are called anonymous because they are not declared in the standard manner by using
the def keyword. lambda keyword is used to create small anonymous functions.
Lambda forms can take any number of arguments but return just one value in the form of an
expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an expression
Lambda functions have their own local namespace and cannot access variables other than those in
their parameter list and those in the global namespace.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]] : expression
For Example1
Output
30
40
For Example2
a=lambdab:b+15;
print(a(15))
Output
30
For Example3
a=lambdab, c:b*c;
print(a(6,5))
Output
30
Partial functions allow user to fix a certain number of arguments of a function and generate a new
function.Partial functional application in python is implemented through functools library.
For Example 1
g = partial(f, 3, 1, 4)
print(g(5))
Output
48
For Exampl 2
fromfunctools import *
defadd(a, b, c):
d = 10*a + 5*b + c
returnd
g = partial(add, c = 2, b = 5)
print(g(5))
Output
77
Python Generators:
A generator is a function that returns an iterator that produces a sequence of values when iterated over. It
traverses the entire items at once.A generator function is similar to a regular function, but instead of a return
statement, it has a yield keyword.Generators are useful when user wants to produce a large sequence of
values, but don't want to store all of them in memory at once.If there is no value found in iteration, it
raises StopIteration exception.
Because the values from the generator object are fetched one at a time rather than the entire list at once, so
user can use a for-loop, next(), or list() function to get the actual values.
Syntax
defgenerator_name(arguments) :
statements
.
.
yield<value/variable>
For Example 1 Write a program to print the table of the given number using the generator.
def table(n):
for i in range(1,11):
yield n*i
for i in table(15):
print(i)
def multiple_yield():
str1 = "First String"
yield str1
obj = multiple_yield()
print(next(obj))
print(next(obj))
print(next(obj))
The difference between yield and return is that yield returns a value and pauses the execution while
maintaining the internal states, whereas the return statement returns a value and terminates the execution
of the function.
Import NumPy
Once NumPy is installed, it can be imported in the application by adding the import keyword.
import numpy
For Example
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
NumPy as np
NumPy is usually imported under the np alias. In Python alias are an alternate name for referring to the same
thing.
Syntax
For Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
NumPy is used to work with arrays. The array object in NumPy is called ndarray.NumPy ndarray object is
created by using the array() function.To create an ndarray, a list, tuple or any array-like object is passed
into the array() method, and it will be converted into an ndarray.
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
For Example 2 Creating NumPy array using list
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Dimensions in Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
import numpy as np
arr = np.array(42)
print(arr)
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
An array that has 1-D arrays as its elements is called a 2-D array.These are often used to represent
matrix or 2nd order tensors.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
An array that has 2-D arrays (matrices) as its elements is called 3-D array.These are often used to
represent a 3rd order tensor.
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
NumPy Arrays provides the ndim attribute that returns an integer that tells how many dimensions the array
have.
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
Array indexing is the same as accessing an array element. An array element can access by referring to its
index number.The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the
second has index 1 etc.
For Example Get the first element from the following array(1D):
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0])
To access elements from 2-D arrays we can use comma separated integers representing the
dimension and the index of the element.
For Example Access the element on the first row, second column:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st row: ', arr[0, 1])
To access elements from 3-D arrays we can use comma separated integers representing the
dimensions and the index of the element.
For Example Access the third element of the second array of the first array:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
Negative Indexing
For Example: Print the last element from the 2-D array
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('Last element from 2nd dim: ', arr[1, -1])
Slicing in python means taking elements from one given index to another given index.In other words Slicing
NumPy arrays means extracting elements from an array in a specific range.NumPy arrays use
brackets [] and : notations for slicing.
Syntax
[start:end:step]
The default value of start is 0, step is 1 and end is length of array in that dimension.
a[:n] Select elements starting with index 0 and up to element with index n-1
a[m:] Select elements starting with index m and up to the last element
For Example 1 Slice elements from index 1 to index 5 from the following array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])
For Example2 Slice elements from index 4 to the end of the array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[4:])
For Example4 Slice elements from index 2 to index 6(not included) with a step value 2:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[2:6:2])
Negative Slicing
For Example Slice from the index 3from the end to index 1from the end:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])
For Example 1 From the second element, slice elements from index 1 to index 4(not included)
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4])
NumPy has some extra data types, and refer to data types with one character, like i for integers, u for
unsigned integers etc.
Below is a list of all data types in NumPy and the characters used to represent them.
i - integer
b - boolean
u - unsigned integer
f - float
c - complex float
m - timedelta
M - datetime
O - object
S - string
U - unicode string
V - fixed chunk of memory for other type ( void )
The NumPy array object has a property called dtype that returns the data type of the array:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.dtype)
The array( ) function is used to create arrays, this function can take an optional argument: dtype that
allows to define the expected data type of the array elements:
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='S')
print(arr)
print(arr.dtype)
If a type is given in which elements can't be casted then NumPy will raise a ValueError.
import numpy as np
arr = np.array(['a', '2', '3'], dtype='i')
A non integer string like ‘a’ can not be converted to integer (will raise an error).
The best way to change the data type of an existing array, is to make a copy of the array with
the astype() method.
The astype() function creates a copy of the array, and allows to specify the data type as a parameter.
The data type can be specified using a string, like 'f' for float, 'i' for integer etc. or can use the data type
directly like float for float and int for integer.
For Example 1 Change data type from float to integer by using ‘i' as parameter
import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)
For Example 2 Change data type from float to integer by using ‘int' as parameter
import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype(int)
print(newarr)
print(newarr.dtype)
import numpy as np
arr = np.array([1, 0, 3])
newarr = arr.astype(bool)
print(newarr)
print(newarr.dtype)
COPY: The copy owns the data and any changes made to the copy will not affect original array, and
any changes made to the original array will not affect the copy.
For Example Make a copy, change the original array, and display both arrays
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy( )
arr[0] = 42
print(arr)
print(x)
VIEW: The view does not own the data and any changes made to the view will affect the original
array, and any changes made to the original array will affect the view.
For Example Make a view, change the original array, and display both arrays
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view( )
arr[0] = 42
print(arr)
print(x)
Every NumPy array has the attribute base that returns None if the array owns the data. Otherwise,
the base attribute refers to the original object.
For Example Print the value of the base attribute to check if an array owns it’s data or not
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy( )
y = arr.view( )
print(x.base)
print(y.base)
The shape of an array is the number of elements in each dimension. NumPy arrays have an attribute
called shape that returns a tuple with each index having the number of corresponding elements.
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)
It returns (2, 4), which means that the array has 2 dimensions, where the first dimension has 2 elements and
the second has 4.
Reshaping means changing the shape of an array. By reshaping we can add or remove dimensions or change
number of elements in each dimension.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3)
print(newarr)
It returns a 2-D array where outermost dimension will have 4 arrays, each with 3 elements.
Addition
The add( ) function sums the content of two arrays, and return the results in a new array.
import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.add(arr1, arr2)
print(newarr)
Subtraction
The subtract( ) function subtracts the values from one array with the values from another array, and
return the results in a new array.
import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.subtract(arr1, arr2)
print(newarr)
Multiplication
The multiply( ) function multiplies the values from one array with the values from another array, and
return the results in a new array.
import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.multiply(arr1, arr2)
print(newarr)
Division
The divide( ) function divides the values from one array with the values from another array, and
return the results in a new array.
import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.divide(arr1, arr2)
print(newarr)
Power
The power( ) function rises the values from the first array to the power of the values of the second
array, and return the results in a new array.
import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.power(arr1, arr2)
print(newarr)
Remainder
Both the mod( ) and the remainder( ) functions return the remainder of the values in the first array
corresponding to the values in the second array, and return the results in a new array.
import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.mod(arr1, arr2)
print(newarr)
Psuedorandom number generation
Python defines a set of functions that are used to generate or manipulate random numbers through
the random module.
Random numbers generated through a generation algorithm are called pseudo random. Functions in the
random module rely on a pseudo-random number generator function random( ), which generates a
random float number between 0.0 and 1.0. These particular type of functions is used in a lot of games,
lotteries, or any application requiring a random number generation.
NumPy offers the random module to work with random numbers. The randint( ) method is used to generate
random integer numbers.
The random module's rand( ) method returns a random float between 0 and 1.
The randint( ) method takes a size parameter where you can specify the shape of an array.
For Example 1 Generate a 1-D array containing 5 random integers from 0 to 100
For Example 2 Generate a 2-D array with 3 rows, each row containing 5 random integers from 0 to 100
The rand( ) method also allows you to specify the shape of the array.
For Example 2 Generate a 2-D array with 3 rows, each row containing 5 random float numbers
The choice( ) method allows to generate a random value based on an array of values. The choice(
) method takes an array as a parameter and randomly returns one of the values.
The choice( ) method also allows to return an array of values. Add a size parameter to specify the shape
of the array.
For Example Generate a 2-D array that consists of the values in the array parameter (3, 5, 7, and 9)
Using random.sample( )
The random module also provides the sample( ) method, which directly generates a list of random numbers.
For Example
import random
#Generate 5 random numbers between 10 and 30
random_list = random.sample(range(10, 40), 6)
print(random_list)
Classes & Objects
Python is an object oriented programming language. Almost everything in Python is an object, with its
properties and methods.
Class
The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and
methods. The keyword class is used for creating classes.
Syntax:
class <class_name> :
statement 1
.
.
.
Statement n
Example:
class bike:
gear = 0
name = “TVS”
Class creates a user-defined data structure, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A class is like a blueprint for an
object.
Some points on Python class:
Classes are created by keyword class.
Attributes are the variables that belong to a class.
Attributes are always public and can be accessed using the dot (.) operator.
Objects
The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard,
chair, table, pen, etc.
Syntax:
<object_name> = class_name(<arguments>)
Example:
class bike:
gear = 0
name = “TVS”
# object creation
b = bike( )
print(b.name)
Methods
The method is a function that is associated with an object. In Python, a method is not unique to class
instances. Any object type can have methods.
Example:
# create a class
class room:
length = 0.0
breadth = 0.0
def cal_area(self) :
area = self.length * self.breadth
print(“Area of Room = “, area)
Constructors in Python
Constructors are generally used for instantiating an object. The task of constructors is to initialize(assign
values) to the data members of the class when an object of the class is created. In Python the __init__( )
method is called the constructor and is always called when an object is created. It accepts the self-keyword
as a first argument which allows accessing the attributes or method of the class.
Syntax:
def __init__(self) :
statements
Types of constructors :
Default constructor: The default constructor is a simple constructor which doesn’t accept any
arguments. Its definition has only one argument which is a reference to the instance being constructed.
class student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello", name)
student = student1( )
student.show("John")
Parameterized constructor: Constructor with parameters is known as parameterized constructor. The
parameterized constructor takes its first argument as a reference to the instance being constructed
known as self and the rest of the arguments are provided by the programmer.
class student:
# Constructor - non parameterized
def __init__(self, name):
self.name = name
print("This is non parametrized constructor")
def show(self):
print("Hello", self.name)