0% found this document useful (0 votes)
5 views84 pages

Python Array Basics and Usage Guide

The document discusses the concept of arrays in Python, explaining their advantages over using multiple variables for storing data. It outlines how arrays can store elements of the same datatype, dynamically adjust their size, and offers examples of creating and manipulating arrays. Additionally, it covers indexing and slicing techniques for accessing array elements.

Uploaded by

Het Patel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views84 pages

Python Array Basics and Usage Guide

The document discusses the concept of arrays in Python, explaining their advantages over using multiple variables for storing data. It outlines how arrays can store elements of the same datatype, dynamically adjust their size, and offers examples of creating and manipulating arrays. Additionally, it covers indexing and slicing techniques for accessing array elements.

Uploaded by

Het Patel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

FET – B.

Tech (CS & E)

Computer Programming Paradigm (Python)


(2601102)

Unit 2.2 Array


c h
Te
B .
T
Prepared By: Dr. Tejaskumar Bhatt
E
F )
S
L &E
G S
(C
Reference:
• Rao, R. N. (2009). Core Python programming (2nd ed.). Dreamtech Press
• Chun, W. (2007). Core Python programming (1st ed.). Pearson.
• Lutz, M. (2013). Learning Python (5th ed.). O'Reilly Media.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

Array
 Why Array?
 Suppose there is a group of students whose marks are to be listed. The first student’s marks are
stored in a variable m1, the second student’s marks are stored in m2, the third student’s marks in
m3, and so on and the 100 th student’s marks are stored in m100. It means, we are supposed to
create 100 variables to store 100 students’ marks.
 Thus, we are supposed to write 100 statements like this:

h
 m1=61

ec
.T
 m2=57

B
 m3=82

E) T
S& FE
 :
 m100=70
(C LS
 Now, if we want to display these marks, we need to write another 100 statements. It means, a
G

simple program will contain hundreds of statements and this becomes difficult for the
programmer.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

Array
 Why Array?
 On the other hand, just imagine there is only one variable that stores 100 students’
marks.
 That variable will be very much useful to us since we have to write only 1 statement
instead of writing 100 statements.

h
 For example, we can declare ‘m’ variable as an array and store all the marks there.

ec
 This reduces the program size considerably and the programmer’s task will become easy.

.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Array
 What is an array?
 An array is an object that stores a group of elements (or values) of same datatype. The
main advantage of any array is to store and process a group of elements easily.
 There are two points we should remember in case of arrays in Python.
1. Arrays can store only one type of data. It means, we can store only integer type elements

h
or only float type elements into an array. But we cannot store one integer, one float and

ec
one character type element into the same array.

.T
B
2. Arrays can increase or decrease their size dynamically. It means, we need not declare the

E) T
size of the array. When the elements are added, it will increase its size and when the
S& FE
elements are removed, it will automatically decrease its size in memory.
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Array
 Advantages of Arrays
 Arrays are similar to lists. The main difference is that arrays can store only one type of
elements; whereas, lists can store different types of elements. When dealing with a huge
number of elements, arrays use less memory than lists and they offer faster execution
than lists.
 The size of the array is not fixed in Python. Hence, we need not specify how many

h
ec
elements we are going to store into an array in the beginning.

.T
 Arrays can grow or shrink in memory dynamically (during runtime).

B
 Arrays are useful to handle a collection of elements like a group of numbers or

E) T
characters.
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Array
Creating an Array
 The array object as: arrayname = array(type code, [elements])
 The type code ‘i’, represents integer type array where we can store integer numbers. If
the type code is ‘f’ then it represents float type array where we can store numbers with
decimal point.

h
ec
.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Array
Creating an Array
 We should first write the module name ‘array’ and then the type code we can use is ‘i’
for integer type array.
 After that the elements should be written inside the square braces [ ] as,
 a = array(‘i’, [4, 6, 2, 9])

h
 creating an array whose name is ‘a’ with integer type elements 4, 6, 2 and 9.

ec
 to create a float type array, we can write:

.T
B
 arr = array(‘d’, [1.5, -2.2, 3, 5.75])

E) T
S& FE
 create an array by the name ‘arr’ with float type elements 1.5, -2.2, 3.0 and 5.75.
 The type code is ‘d’ which represents double type elements each taking 8 bytes memory.
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Array
Importing the Array Module
 There are three ways to import the array module into our program.
 The first way is to import the entire array module using import statement as,
 import array
 a=[Link]('i',[4,6,2,9])

h
 When we import the array module, we are able to get the ‘array’ class of that module that

ec
.T
helps us to create an array.

B
 Here, the first ‘array’ represents the module name and the next ‘array’ represents the

E) T
class name for which the object is created
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Array
Importing the Array Module
 The second way of importing the array module is to give it an alias name, as:
 import array as ar
 a=[Link]('i', [4,6,2,9])
 Here, the array is imported with an alternate name ‘ar’. Hence we can refer to the array class of

h
‘ar’ module as:

ec
 The third way of importing the array module is to write:

.T
B
 from array import *

E) T
 Observe the ‘*’ symbol that represents ‘all’.
S& FE
 The meaning of this statement is this:import all (classes, objects, variables etc) from the array
(C LS
module into our program.
G

 That means we are specifically importing the ‘array’ class (because of * symbol) of ‘array’
module. So, there is no need to mention the module name before our array name while creating
it.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

Array
A Python program to create an integer type array.
 # creating an array
 import array
 a = [Link]('i', [5, 6, -7, 8])
 print('The array elements are: ')
 for element in a:

h
ec
 print(element)

.T
B
E) T
 O/P C:\>python [Link]
 5 S& FE
(C LS
 6
G

 -7
 8
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

Array
A Python program to create an integer type array.
 # creating an array – v 2.0
 from array import *
 a = array('i', [5, 6, -7, 8])
 print('The array elements are: ')
 for element in a:

h
ec
 print(element)

.T
B
E) T
 O/P C:\>python [Link]
 5 S& FE
(C LS
 6
G

 -7
 8
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)

Array
A Python program to create an array with a group of characters.
 # creating an array with characters
 from array import *
 arr = array('u', ['a','b','c','d','e'])
 print('The array elements are: ')
 for ch in arr:

h
 print(ch)

ec
O/P C:\>python

.T
[Link]

B
a

E) T
S& FE
b
c
(C LS
d
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Task
Task for the Array
 Create and display an array.
 Find the length of an array.
 Access elements by index.
 Update an element in an array.
 Sort Array in Ascending Order

h
ec
 Insert an element at a given index.

.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Indexing and Slicing on Arrays
 An index represents the position number of an element in an array.

 we can understand that the 0th element of the array is represented by x[0], the 1st element is
represented by x[1] and so on. Here, 0, 1, 2, etc, are representing the position numbers of the

h
ec
elements.

.T
 So, in general we can use i to represent the position of any element. This ‘i’ is called ‘index’ of

B
the array. Using ‘index, we can refer to any element of the array as x[i] where ‘i’ values will

E) T
change from 0 to n-1.
S& FE
 Here n represents the total number of elements in the array
(C LS
 To find out the number of elements in an array we can use the len() function as: n = len(x)
G

 The len(x) function returns the number of elements in the array ‘x’ into ‘n

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Indexing and Slicing on Arrays
A Python program to retrieve the elements of an array using array index.
# accessing elements of an array using index
from array import *
x = array('i', [10, 20, 30, 40, 50])
n = len(x) # find number of elements in the array

h
ec
# display array elements using indexing

.T
for i in range(n): # repeat from 0 to n-1

B
print(x[i], end=' ')

E) T
S& FE
(C LS
G

O/P C:\>python [Link]


10 20 30 40 50
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Indexing and Slicing on Arrays

A Python program to retrieve elements of an array using while loop.


# accessing elements of an array using index - v 2.0

from array import *


x = array('i', [10, 20, 30, 40, 50])
n = len(x) # find number of elements in the array
I=0 # display array elements using indexing

h
while i<n:

ec
print(x[i], end=' ')

.T
i+=1

B
E) T
O/P C:\>python [Link] S& FE
(C LS
10 20 30 40 50
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Indexing and Slicing on Arrays
 A slice represents a piece of the array.
 When we perform ‘slicing’ operations on any array, we can retrieve a piece of
the array that contains a group of elements.
 Whereas indexing is useful to retrieve element by element from the array,
slicing is useful to retrieve a range of elements.
 The general format of a slice is: arrayname[start:stop:stride]

h
ec
 We can eliminate any one or any two in the items: ‘start’, ‘stop’ or ‘stride’ from

.T
the above syntax. For example, arr[1:4]

B
 slice gives elements starting from 1st to 3rd from the array ‘arr’.

E) T
S& FE
 Counting of the elements starts from 0.
 All the items ‘start’, ‘stop’ and ‘stride’ represent integer numbers either positive
(C LS
or negative.
G

 The item ‘stride’ represents step size excluding the starting element.

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Indexing and Slicing on Arrays
 A Python program to retrieve and display only a range of elements from an
array using slicing.
 # using slicing to display elements of an array.
 from array import *
 x = array('i', [10, 20, 30, 40, 50, 60, 70])
 for i in x[2:5]:

h
# display elements from 2nd to 4th only

ec
 print(i)

.T
B
 Output: C:\>python [Link]

E) T
 30
S& FE
(C LS
 40
G

 50

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Indexing and Slicing on Arrays
 A Python program that helps to know the effects of slicing operations on an
array.
# create array y with elements from 1st to 3rd from x
y = x[1:4]
print(y)

# create array y with elements from 0th till the last element in x

h
ec
y = x[0:]

.T
print(y)

B
# create array y with elements from 0th to 3rd from x

E) T
S& FE
y = x[:4]
print(y)
(C LS
G

# create array y with last 4 elements from x


y = x[-4:]
print(y)
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Indexing and Slicing on Arrays
 A Python program that helps to know the effects of slicing operations on an
array.
# create y with last 4th element and with 3 [-4-(-1)= -3]elements towards right.
y = x[-4: -1]
print(y)

# create y with 0th to 7th elements from x.

h
ec
#stride 2 means, after 0th element, retrieve every 2nd element from x

.T
y = x[0:7:2]

B
print(y)

E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)

Task
Task for the Indexing and Slicing on Arrays
 Access first element
 Access last element
 Change element by index
 Slice first three elements
 Slice last three elements

h
ec
 Slice with step

.T
 Slice reverse

B
 Slice from index 2 to 5

E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Processing the Arrays
 The arrays class of
arrays module in
Python offers methods
to process the arrays
easily
 Methods are generally
called as:
[Link]().

h
ec
.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Processing the Arrays
A Python program to understand various methods of arrays class.
from array import*
# create an array with int values
arr = array('i', [10,20,30,40,50])
print('Original array: ', arr)

# append 30 to the array arr


[Link](30)

h
ec
[Link](60)
print('After appending 30 and 60: ', arr)

.T
B
# insert 99 at position number 1 in arr

E) T
[Link](1, 99)

S& FE
print('After inserting 99 in 1st position: ', arr)
(C LS
# convert an array into a list using tolist() method
lst = [Link]()
G

print('List: ', lst)


print('Array: ', arr)

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Processing the Arrays
A Python program to understand various methods of arrays class.
from array import*
# remove an element from arr
[Link](20)
print('After removing 20: ', arr)

# remove last element using pop() method

h
n = [Link]()

ec
print('Array after using pop(): ', arr)

.T
print('Popped element: ', n)

B
E) T
# finding position of element using index() method

S& FE
n = [Link](30)
print('First occurrence of element 30 is at: ', n)
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Processing the Arrays
A Python program to understand various methods of arrays class.
C:\>python [Link]
Original array: array('i', [10, 20, 30, 40, 50])

After appending 30 and 60: array('i', [10, 20, 30, 40, 50, 30, 60])
After inserting 99 in 1st position: array('i', [10, 99, 20, 30, 40,50, 30, 60])
After removing 20: array('i', [10, 99, 30, 40, 50, 30, 60])

h
Array after using pop(): array('i', [10, 99, 30, 40, 50, 30])

ec
Popped element: 60

.T
First occurrence of element 30 is at: 2

B
List: [10, 99, 30, 40, 50, 30]

E) T
Array: array('i', [10, 99, 30, 40, 50, 30])

S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Task
1. Append element to array
2. Insert element at specific index
3. Pop last element
4. Pop element at given index
5. Remove a specific value

h
6. Convert List to Array (fromlist)

ec
7. Convert array to list

.T
B
8. Find Index of an Element

E) T
9. Reverse the array
[Link] an Element S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Types of Arrays
1. Single dimensional arrays:
 These arrays represent only one row or one column of elements. For example,
marks obtained by a student in 5 subjects can be written as ‘marks’ array, as:
marks = array('i', [50, 60, 70, 66, 72])
 The above array contains only one row of elements. Hence it is called single
dimensional array or one dimensional array.

h
ec
.T
2. Multi-dimensional arrays:

B
 These arrays represent more than one row and more than one column of elements.

E) T
 For example, marks obtained by 3 students each one in 5 subjects can be written
as ‘marks’ array as: S& FE
(C LS
 marks = array([[50, 60, 70, 66, 72],
G

 [60, 62, 71, 56, 70],


 [55, 59, 80, 68, 65]])
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Types of Arrays
 The first student’s marks are written in first row.
 The second student’s marks are in second row and
 The third student’s marks are in third row.
 In each row, the marks in 5 subjects are mentioned.
 Thus this array contains 3 rows and 5 columns and hence it is called multi-

h
dimensional array.

ec
 Each row of the above array can be again represented as a single dimensional

.T
array.

B
 Thus the above array contains 3 single dimensional arrays. Hence, it is called a

E) T
S& FE
two dimensional array.
 A two dimensional array is a combination of several single dimensional arrays.
(C LS
 Similarly, a three dimensional array is a combination of several two
G

dimensional arrays.

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Types of Arrays
 In Python, we can create and work with single dimensional arrays only. So far,
the examples and methods discussed by us are applicable to single
dimensional arrays.
 Python does not support multi-dimensional arrays.

 But that is not a bad news. We can construct multidimensional arrays using

h
ec
third party packages like numpy (numerical python).

.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Working with Arrays using numpy
 numpy is a package that contains several classes, functions, variables etc. to deal
with scientific calculations in Python.
 numpy is useful to create and also process single and multi-dimensional arrays.
 In addition, numpy contains a large library of mathematical functions like linear
algebra functions and Fourier transforms.
 To get complete help on numpy, the reader can refer to the following link at

h
ec
 [Link]: [Link]

.T
 The arrays which are created using numpy are called n dimensional arrays where n

B
can be any integer.

E) T
 If n=1, it represents a one dimensional array. If n=2, it is a two dimensional array.
S& FE
Similarly, if n=3, it is a three dimensional array.
(C LS
 The arrays created in numpy can accept only one type of elements. We cannot store
G

different datatypes into same array.


 To work with numpy, we should first import numpy module into our Python
programs as: import numpy
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Working with Arrays using numpy
 V1: A Python program to create a simple array using numpy.
 # creating single dimensional array using numpy
 import numpy
 arr = [Link]([10, 20, 30, 40, 50]) # create array
 print(arr) # display array

 V2: A Python program to create a simple array using numpy.

h
ec
 # creating single dimensional array using numpy - v2.0

.T
import numpy as np
Output:

B
arr = [Link]([10, 20, 30, 40, 50]) # create array C:\>python [Link]
 print(arr) # display array

E) T
[10, 20, 30, 40,

S& FE
50]
 V3: A Python program to create a simple array using numpy.
(C LS
 # creating single dimensional array using numpy - v3.0
G

 from numpy import *


 arr = array([10, 20, 30, 40, 50]) # create array
 print(arr) # display array
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Working with Arrays using numpy

 Creating arrays in numpy can be done in several ways.


1. Using array() function
2. Using linspace() function
3. Using logspace() function
4. Using arange() function

h
ec
5. Using zeros() and ones() functions

.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Working with Arrays using numpy
1. Using array() function
 We can call array() function of numpy module to create an array. When we create
an array, we can specify the datatype of the elements either as ‘int’ or ‘float’. We
can create an integer type array as:
 arr = array([10, 20, 30, 40, 50], int)

h
 arr = array([1.5, 2.5, 3, 4, -5.1], float)

ec
 To create an array with character type elements, we need not specify the datatype.

.T
B
We can simply write: arr = array(['a', 'b', 'c', 'd'])

E) T
 To create a string type array where can store a group of strings, we should use
S& FE
additional attribute ‘dtype = str’ in the array() function as:
(C LS
 arr = array(['Delhi', 'Hyderabad', 'Mumbai', 'Ahmedabad'], dtype=str)
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Working with Arrays using numpy
1. Using array() function
 # Program: Demonstration of creating arrays using [Link]()
 import numpy as np
 int_arr = [Link]([10, 20, 30, 40, 50], int) # Integer array
 print("Integer Array:", int_arr)

 float_arr = [Link]([1.5, 2.5, 3, 4, -5.1], float)

h
# Float array

ec
 print("Float Array:", float_arr)

.T
B
 char_arr = [Link](['a', 'b', 'c', 'd']) # Character array

E) T
 print("Character Array:", char_arr)
S& FE
(C LS
# String array
G

string_arr = [Link](['Delhi', 'Hyderabad', 'Mumbai', 'Ahmedabad'], dtype=str)


print("String Array:", string_arr)

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Working with Arrays using numpy
1. Using array() function
 # Program: Demonstration of creating arrays using [Link]()
 # Displaying datatype of each array

 print("\nData types of arrays:")

 print("int_arr dtype :", int_arr.dtype)

h
 print("float_arr dtype :", float_arr.dtype)

ec
 print("char_arr dtype :", char_arr.dtype)

.T
B
 print("string_arr dtype:", string_arr.dtype)

E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Working with Arrays using numpy
2. Using linspace() function
 The linspace() function is used to create an array with evenly spaced points
between a starting point and ending point.

 The form of the linspace() function is: linspace(start, stop, n)

 ‘start’ represents the starting element

h
ec
 ‘stop’ represents the ending element.

.T
 ‘n’ is an integer that represents the number of parts the elements should be

B
divided.

E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Working with Arrays using numpy
2. A Python program to creating an array with 5 equal points using linspace().
 # creating an array using linspace()
 from numpy import *
 # divide 0 to 10 into 5 parts and take those points in the array
 a = linspace(0, 10, 5)
 print('a = ', a)

h
ec
 Let’s take one example to understand this. a = linspace(0, 10, 5)

.T
 In the above statement, we are creating an array ‘a’ with starting element 0 and

B
ending element 10.

E) T
 This range is divided into 5 equal parts and hence the points will be 0, 2.5, 5, 7.5
and 10.
S& FE
 These elements are stored into ‘a’. Please remember the staring and elements 0 and
(C LS
10 are included. Program 20 shows how to create an array with 5 equal points
G

using the linspace() function.


 If ‘n’ is omitted, then it is taken as 50

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Working with Arrays using numpy
1. Program: Demonstration of creating arrays using [Link]()
2. import numpy as np
 # Example 1: Generate 10 values between 0 and 1
2. arr1 = [Link](0, 1, 10)
3. print("Array from 0 to 1 with 10 values:\n", arr1)

h
ec
 # Example 2: Generate 5 values between 10 and 50

.T
2. arr2 = [Link](10, 50, 5)

B
E) T
3. print("\nArray from 10 to 50 with 5 values:\n", arr2)

S& FE
(C LS
 # Example 3: Generate 7 values between 0 and 2π (pi)
G

2. arr3 = [Link](0, 2 * [Link], 7)


3. print("\nArray from 0 to 2π with 7 values:\n", arr3)
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Working with Arrays using numpy
2. Program: Demonstration of creating arrays using [Link]()

 # Example 4: Including endpoint = False

2. arr4 = [Link](1, 5, 5, endpoint=False)

3. print("\nArray from 1 to 5 with 5 values (excluding endpoint):\n", arr4)

h
ec
.T
 # Example 5: Returning both array and step size

B
E) T
2. arr5, step = [Link](0, 20, 6, retstep=True)

S& FE
3. print("\nArray from 0 to 20 with 6 values:\n", arr5)
(C LS
4. print("Step size between values:", step)
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Working with Arrays using numpy
2. Program: Demonstration of creating arrays using [Link]()
3. Output:
 Array from 0 to 1 with 10 values:
2. [0. 0.11111111 0.22222222 0.33333333 0.44444444
3. 0.55555556 0.66666667 0.77777778 0.88888889 1. ]

 Array from 10 to 50 with 5 values:

h
2. [10. 20. 30. 40. 50.]

ec
.T
 Array from 0 to 2π with 7 values:

B
2. [0. 1.04719755 2.0943951 3.14159265 4.1887902 5.23598776 6.28318531]

E) T
S& FE
 Array from 1 to 5 with 5 values (excluding endpoint):
2. [1. 1.8 2.6 3.4 4.2]
(C LS
 Array from 0 to 20 with 6 values:
G

2. [ 0. 4. 8. 12. 16. 20.]


3. Step size between values: 4.0

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Working with Arrays using numpy
Creating Arrays using logspace() function
 The logspace() function is similar to linspace().
 The linspace() function produces the evenly spaced points. Similarly, logspace()
produces evenly spaced points on a logarithmically spaced scale.
 The logspace() function is used in the following format: logspace(start, stop, n)
 The logspace() function starts at a value which is 10 to the power of ‘start’

h
ec
 ends at a value which is 10 to the power of ‘stop’.

.T
 If ‘n’ is not specified, then its value is taken as 50.

B
 eg. a = logspace(1, 4, 5)

E) T
S& FE
 This function represents values starting from 101 to 104. These values are divided into
5 equal points and those points are stored into the array ‘a’.
(C LS
 O/P: 10.0 56.2 316.2 1778.3 10000.0
G

 [ 101=10.0 ,101.75≈56.23 102.5≈316.23 103.25≈ 1778.28 104=10000.0 ]

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Working with Arrays using numpy
A Python program to create an array using logspace().
2. # creating an array using logspace()
3. from numpy import *
4. # divide the range: 10 power 1 to 10 power 4 into 5 equal parts and take those
points in the array
5. a = logspace(1, 4, 5)

h
6. # find no. of elements in a

ec
7. n = len(a)

.T
B
8. # repeat from 0 to n-1 times

E) T
9. for i in range(n):

S& FE
10. print('%.1f' % a[i], end=' ') # display 1 digit after decimal point
(C LS
 O/P: 10.0 56.2 316.2 1778.3 10000.0
G

 [ 101=10.0 ,101.75≈56.23 102.5≈316.23 103.25≈ 1778.28 104=10000.0 ]

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Working with Arrays using numpy
Creating Arrays using arange() Function
 The arange() function in numpy is same as range() function in Python. The
arange() function is used in the following format: arange(start, stop, stepsize)
 This creates an array with a group of elements from ‘start’ to one element prior to
‘stop’ in steps of ‘stepsize’.
 If the ‘stepsize’ is omitted, then it is taken as 1. If the ‘start’ is omitted, then it is

h
ec
taken as 0

.T
 eg. arange(10) will produce an array with elements 0 to 9.

B
 eg. arange(5, 10)will produce an array with elements from 5 to 9.

E) T
S& FE
 eg. arange(1, 10, 3) will create an array with the elements starting from 1 to 9.
(C LS
So, the first element will be 1. Since the stepsize is 3, we should 3 to get the
subsequent elements. Thus, the second element can be obtained as 1+3 = 4 and
G

the third element can be obtained as 4+3 = 7 and so on. Hence, the array will
contain the following elements: [ 1 4 7]
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Working with Arrays using numpy
Creating Arrays using arange() Function
 eg. arange(10, 1, -1) Since the stepsize is -1, it represents the elements in
descending order from 10 to 2, as: [10 9 8 7 6 5 4 3 2].
 Arange(0, 10, 1.5) In this case, the array elements will be: [0. 1.5 3. 4.5 6. 7.5
9. ].
 A Python program to create an array with even number up to 10.

h
ec
 # creating an array with even numbers up to 10

.T
 from numpy import *

B
 # create an array using arange() function

E) T
 a = arange(2, 11, 2)
 print(a)
S& FE
(C LS
 The starting even number is 2 and everytime we are adding 2 (stepsize) to get the
next even number. This will continue till 10 (one element prior to 11).
G

 O/P: [ 2 4 6 8 10]

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Working with Arrays using numpy
Creating Arrays using zeros() and ones() Functions
 We can use the zeros() function to create an array with all zeros. The ones()
function is useful to create an array with all 1s.
 They are written in the following format:
 zeros(n, datatype)
 ones(n, datatype)

h
ec
 where ‘n’ represents the number of elements. we can eliminate the ‘datatype’

.T
argument. If we do not specify the ‘datatype’, then the default datatype used by

B
numpy is ‘float’.

E) T
S& FE
 examples: zeros(5) 5 elements all are zeros, as: [ 0. 0. 0. 0. 0. ]
 eg. zeros(5, int) this will create an array as: [ 0 0 0 0 0 ].
(C LS
 eg. ones(5, float) will create an array with 5 integer elements all are 1s
G

 as: [ 1. 1. 1. 1. 1. ].

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Working with Arrays using numpy
A Python program to create arrays using zeros() and ones().
 # creating arrays using zeros() and ones()
 from numpy import *
 a = zeros(5, int)
 print(a)
 b = ones(5)

h
ec
 print(b) # default datatype is float

.T
B
E) T
 O/P; C:\>python [Link]
 [0 0 0 0 0]
S& FE
(C LS
 [1. 1. 1. 1. 1.]
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Task for Working with Arrays using numpy

Using array()
1. prog1() → Create integer array
2. prog2() → Create float array
3. prog3() → Create array with negative numbers
4. prog4() → Mixed values (int + float) array

h
ec
5. prog5() → Create 2D array (matrix)

.T
6. prog6() → Array with step values (manual list)

B
E) T
7. prog7() → Square of array elements

S& FE
8. prog8() → Add scalar value to array (# add 5 to each element)
(C LS
9. prog9() → Element-wise addition of two arrays
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Task for Working with Arrays using numpy

Using linspace()
1. prog11() → Generate 5 values between 0 and 10
2. prog12() → Generate 11 values between 0 and 100
3. prog13() → Generate 9 values between 1 and 5
4. prog14() → linspace without endpoint

h
ec
5. prog15() → Sine function values between 0 and 2π

.T
6. prog16() → Divide 0–1 into 20 equal parts

B
E) T
7. prog18() → linspace with spacing (retstep=True)

S& FE
8. prog19() → Values between -5 and 5
(C LS
9. prog20() → linspace with integer type values
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Task for Working with Arrays using numpy

Using logspace()
1. prog21() → logspace between 10¹ and 10²
2. prog22() → logspace between 10² and 10⁴ (default base 10)
3. prog23() → logspace with base 2
4. prog24() → 50 logspace points from 10⁰ to 10³

h
ec
5. prog25() → Integer logspace values

.T
6. prog26() → logspace without endpoint

B
E) T
7. prog27() → logspace with negative to positive power (-2 to 2)

S& FE
8. prog28() → Multiply logspace values by scalar
(C LS
9. prog29() → Rounded logspace values
G

10.prog30() → Sine of logspace values

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Task for Working with Arrays using numpy

Using arange()
1. prog31() → Sequence from 1 to 10
2. prog32() → Even numbers from 0 to 20
3. prog33() → Reverse sequence 10 to 1
4. prog34() → Floating-point range (0 to 1 with 0.1 step)

h
ec
5. prog35() → Square of numbers from 1 to 10

.T
6. prog36() → Even numbers up to 50

B
E) T
7. prog37() → Odd numbers up to 20

S& FE
8. prog39() → Multiply arange elements by 10
(C LS
9. prog40() → Reverse sequence with step (-2)
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Task for Working with Arrays using numpy

Using zeros() and ones()
1. prog41() → Create array of 5 zeros
2. prog42() → Create array of 5 ones
3. prog43() → 3×3 matrix of zeros
4. prog44() → 2×4 matrix of ones

h
ec
5. prog45() → Zeros array with integer type

.T
6. prog46() → Ones array with integer type

B
E) T
7. prog47() → Ones array multiplied by 7

S& FE
8. prog48() → Replace an element inside ones array
(C LS
9. prog49() → Reshape 12 zeros into 3×4
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Mathematical Operations on Arrays

h
ec
.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Mathematical Operations on Arrays

h
ec
.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Mathematical Operations on Arrays
A Python program to perform some mathematical operations on a numpy array.
 # mathematical operations on arrays
 # import all from numpy module
 from numpy import *
 arr = array([10, 20, 30.5, -40]) # create a numpy array using array() function
 print("Original array: ", arr)

h
ec
 # do arithmetic operations on the elements of the array

.T
 print("After adding 5: ", arr+5)

B
 print("After subtracting 5: ", arr-5)

E) T
S& FE
 print("After multiplying with 5: ", arr*5)
 print("After dividing with 5: ", arr/5)
(C LS
 print("After modulus with 5: ", arr%5)
G

 # we can use the arrays in expressions also


 print("Expression value: ", (arr+5)**2-10)

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Mathematical Operations on Arrays
A Python program to perform some mathematical operations on a numpy array.
 # do some math functions
 print("Sin values: ", sin(arr))
 print("Cos values: ", cos(arr))
 print("Tan values: ", tan(arr))
 print("Biggest element: ", max(arr))

h
 print("Smallest element: ", min(arr))

ec
 print("Sum of all elements: ", sum(arr))

.T
 print("Average of all elements: ", mean(arr))

B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Mathematical Operations on Arrays
A Python program to perform some mathematical operations on a numpy array.
 C:\>python [Link]
 Original array: [ 10. 20. 30.5 -40. ]
 After adding 5: [ 15. 25. 35.5 -35. ]
 After subtracting 5: [ 5. 15. 25.5 -45. ]
 After multiplying with 5: [ 50. 100. 152.5 -200. ]

h
 After dividing with 5: [ 2. 4. 6. 1 -8. ]

ec
 After modulus with 5: [ 0. 0. 0.5 -0. ]

.T
 Expression value: [ 215. 615. 1250.25 1215. ]

B
 Sin values: [-0.54402111 0.91294525 -0.79312724 -0.74511316]

E) T
S& FE
 Cos values: [-0.83907153 0.40808206 0.60905598 -0.66693806]
 Tan values: [ 0.64836083 2.23716094 -1.30222389 1.11721493]
(C LS
 Biggest element: 30.5
G

 Smallest element: -40.0


 Sum of all elements: 20.5
 Average of all elements: 5.125
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Task for Mathematical Operations on Arrays

A Python program to perform some mathematical operations on a numpy
array.
array is [40, 10, -20, 50, -10, 35, 20)

Mathematic Operations

h
ec
.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Aliasing the Arrays
 If ‘a’ is an array, we can assign it to ‘b’, as: b = a
 This is a simple assignment that does not make any new copy of the array ‘a’. It
means, ‘b’ is not a new array and memory is not allocated to ‘b’.
 Also, elements from ‘a’ are not copied into ‘b’ since there is no memory for ‘b’.
 We should understand that we are giving a new name ‘b’ to the same array
referred by ‘a’.
 It means the names ‘a’ and ‘b’ are referencing same array. This is called ‘aliasing’.

h
 ‘Aliasing’ is not ‘copying’. Aliasing means giving another name to the existing

ec
object.

.T
 Hence, any modifications to the alias object will reflect in the existing object and

B
vice versa.

E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Aliasing the Arrays
 A Python program to alias an array and understand the affect of aliasing.
 # aliasing an array.
 from numpy import *
 a = arange(1, 6) # create a with elements 1 to 5.
b=a # give another name b to a
 print('Original array: ', a)
 print('Alias array: ', b)

h
 b[0]=99 # modify 0th element of b

ec
 print('After modification: ')

.T
 print('Original array: ', a)

B
 print('Alias array: ', b)

E) T

 S& FE
Output: C:\>python [Link]
Original array: [1 2 3 4 5]
(C LS
 Alias array: [1 2 3 4 5]
G

 After modification:
 Original array: [99 2 3 4 5]
 Alias array: [99 2 3 4 5]
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Viewing and Copying Arrays
 A Python program to alias an array and understand the affect of aliasing.
 We can create another array that is same as an existing array. This is done by the
view() method.
 This method creates a copy of an existing array such that the new array will also
contain the same elements found in the existing array.
 The original array and the newly created arrays will share different memory
locations.

h
 If the newly created array is modified, the original array will also be modified

ec
since the elements in both the arrays will be like mirror images.

.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Viewing and Copying Arrays
 A Python program to create a view of an existing array.
 # creating view for an array
 from numpy import *
 a = arange(1, 6) # create a with elements 1 to 5.
 b = [Link]() # create a view of a and call it b
 print('Original array: ', a)
 print('New array: ', b)

h
 b[0]=99 # modify 0th element of b

ec
 print('After modification: ')

.T
 print('Original array: ', a)

B
 print('New array: ', b)

E) T

 S& FE
Output: C:\>python [Link]
Original array: [1 2 3 4 5]
(C LS
 New array: [1 2 3 4 5]
G

 After modification:
 Original array: [99 2 3 4
 New array: [99 2 3 4 5]
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Viewing and Copying Arrays
 Viewing is nothing but copying only. It is called ‘shallow copying’ as the elements
in the view when modified will also modify the elements in the original array.
 So, both the arrays will act as one and the same.
 Suppose we want both the arrays to be independent and modifying one array
should not affect another array, we should go for ‘deep copying’.
 This is done with the help of copy() method. This method makes a complete copy

h
of an existing array and its elements.

ec
.T
 When the newly created array is modified, it will not affect the existing array or

B
vice versa.

E) T
 There will not be any connection between the elements of the two arrays
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Viewing and Copying Arrays
 A Python program to copy an array as another array.
 # copying an array.
 from numpy import *
 a = arange(1, 6) # create a with elements 1 to 5.
 b = [Link]() # create a copy of a and call it b
 print('Original array: ', a)
 print('New array: ', b)

h
 b[0]=99 # modify 0th element of b

ec
 print('After modification: ')

.T
 print('Original array: ', a)

B
 print('New array: ', b)

E) T


C:\>python [Link]
S& FE
Original array: [1 2 3 4 5]
(C LS
 New array: [1 2 3 4 5]
G

 After modification:
 Original array: [1 2 3 4 5]
 New array: [99 2 3 4 5]
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Slicing and Indexing in numpyArrays
 Slicing refers to extracting a range of elements from the array.
 The format of slicing operation is given here: arrayname[start:stop:stepsize]
 The default value for ‘start’ is 0,
 for ‘stop’ is n (n is number of elements)
 for ‘stepsize’is 1. Counting starts from 0th position.
 Eg. a = [10, 11, 12, 13, 14, 15]
 a[1:6:2]

h
 Here, ‘start’ is 1. So, it will extract from 1st element, i.e. from 11. Since ‘stop’ is 6,

ec
it will stop at one element prior to 6. That means it will stop at 15.

.T
 Since ‘stepsize’ is 2, we should add 2 to the starting index to get the next element

B
index, as: 1+2 = 3rd element and then 3+2= 5th element. So, the following

E) T
elements will be extracted: [11, 13, 15].

S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Slicing and Indexing in numpyArrays
 A Python program to retrieve elements of a numpy array using indexing.
 # indexing an array
 from numpy import *
 # create array a with elements 10 to 15.
 a = arange(10, 16)
 print(a)
 # retrieve from 1st to one element prior to 6th element in steps of 2

h
 a = a[1:6:2]

ec
 print(a)

.T

B
 C:\>python [Link]

E) T
 [10 11 12 13 14 15]
 [11 13 15]
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Slicing and Indexing in numpyArrays
 Suppose, we write a[:] or a[::] without specifying anything for start, stop and
stepsize, it will extract from 0th element till the end of the array. So, all elements
are extracted.
 Suppose, we write a[2:], it starts at 2nd element and ends at last element. So, the
extracted array will be: [12, 13, 14, 15]

 When negative number ‘i’ is used for ‘start’, it should be taken as n+i.

h
 When negative number ‘j’ is used for ‘stop’, it should be taken as n+j.

ec
 When negative number is used for ‘stepsize’, the stepping goes towards smaller

.T
indexes.

B
 Thus, if we write: a[-1:-4:-1]

E) T
 Since there are totally 6 elements in the array ‘a’, we have ‘start’ as 6-1 = 5, ‘stop’

 S& FE
is 6-4=2, and ‘stepsize’ is -1, i.e. going towards least index.
Hence, it will retrieve elements starting from 5th element till one element prior to
(C LS
2nd element going backwards.
G

 So, the retrieved array will be: [15, 14, 13].

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Slicing and Indexing in numpyArrays
 A Python program to understand slicing operations on arrays.
 # slicing an array
 from numpy import *
 a = arange(10, 16) # create array a with elements 10 to 15.
 print(a)
 b = a[1:6:2] # retrieve from 1st to one element prior to 6th element in steps of 2
 print(b)
 b = a[::] # retrieve all elements from a

h
ec
 print(b)

.T
b = a[-2:2:-1]# retrieve from 6-2= 4th to one element prior to 2nd element in

B
decreasing step size.
 print(b)

E) T
S& FE
 b = a[:-2:] # retrieve from 0th to one element prior to 4th element (6-2= 4th)
 print(b)
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Slicing and Indexing in numpyArrays

 A Python program to understand slicing operations on arrays.


 Output: C:\>python [Link]
 [10 11 12 13 14 15]
 [11 13 15]
 [10 11 12 13 14 15]
 [14 13]
 [10 11 12 13]

h
ec
.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Task for mathematical Operations
Write a Python Programs for Mathematical Operations on NumPy Arrays

Mean of array

Median of array

Index of smallest element

Index of largest element

h

Unique elements

ec

Sort array

.T
Concatenate arrays

B

E) T

Sine of array
Cosine of array
S& FE

(C LS

Square root
G


Minimum element

Maximum element

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Task for Aliasing the Arrays
Write a Python Programs for Python Programs for Aliasing Arrays

Simple aliasing of array

Changing original affects alias

Changing alias affects original

Assign alias and add new element

h
ec
.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Task for Viewing and Copying Arrays
Write a Python Programs for Python Programs for Viewing and Copying Arrays

Simple array view

Modify original affects view

Modify view affects original

Deep copy (copy array)
View vs Copy

h

ec
.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Task for Slicing and Indexing in numpyArrays
Write a Python Programs for Slicing and Indexing in numpyArrays

Access a single element by index

Access the last element

Slice first three elements

Slice from index 2 to end
Slice with step value

h

ec

Reverse the array

.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Dimensions of Arrays
 The dimension of an array represents the arrangement of elements in the array. If
the elements are arranged horizontally, it is called a row and if the elements are
arranged vertically, then it is called a column.
 When an array contains only 1 row or only 1 column of elements, it is called
Single dimensional array or one dimensional array (1D array).
 # array with 1 row

h
 arr1 = array([1,2,3,4,5])

ec
 print(arr1) #displays [1 2 3 4 5]

.T
B
 # array with 1 column
 arr2 = array([10,

E) T
S& FE
 20,
 30,
(C LS
 40])
 print(arr2) # diplay [10, 20, 30, 40]
G

 ‘arr1’ represents a 1D array that contains 1 row and ‘arr2’ represents another 1D
array that contains only 1 column.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Dimensions of Arrays
 If an array contains more than 1 row and 1 column, then it is called two
dimensional array or 2D array.
 # create a 2D array with 2 rows and 3 cols in each row
 arr2 = array([[1,2,3],
 [4,5,6]]) # [[1 2 3]
 print(arr2) [4 5 6]]

h
ec
.T
 We can imagine a 2D array as a combination of several 1D arrays. In the above

B
example, each row of ‘arr2’ in turn represents a 1D array.

E) T
S& FE
 Similarly, we can imagine a 3D array as a combination of several 2D arrays.
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Dimensions of Arrays
 creates a 3D array by the name ‘arr3’ that contains two 2D arrays. Each of these
2D arrays contains 2 rows and 3 columns of elements.
 arr3 = array([ [[1,2,3],[4,5,6]],
 [[1,1,1], [1,0,1]] ])
 O/P :

h
ec
 [ [[1 2 3]

.T
 [4 5 6]]

B

E) T
[[1 1 1]
 [1 0 1]] ] S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Matrices in numpy
 In Mathematics, a matrix represents a rectangular array of elements arranged in
rows and columns.
 It means elements are available in a matrix in the form of several rows and
columns.
 If a matrix has only 1 row, it is called a ‘row matrix’.

h
 If a matrix has only 1 column, then it is called a ‘column matrix’.

ec
.T
 We can understand that the row matrix and column matrices are nothing but 1D

B
arrays.

E) T
S& FE
 When a matrix has more than 1 row and more than 1 column, it is called m x n
matrix where m represents the rows and n represents the columns.
(C LS
 Thus, a 2 x 3 matrix contains 2 rows and 3 columns. We can show these matrices
G

using numpy 2D arrays.


 To work with matrices, numpy provides a special object called matrix.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Matrices in numpy
 Syntax: matrix-name = matrix(2D array or string)
 eg. arr = [[1, 2, 3], [4, 5, 6]]
 a= matrix(arr) # o/P [[1 2 3]
 print(a) [4 5 6]]

h
ec
 Another way of creating a matrix is by passing a string with elements to matrix

.T
object as:

B
E) T
 Str = '1 2; 3 4; 5 6' # observe the semicolons after each row of elements
 b = matrix(str) S& FE
(C LS
 O/P:[[1 2] # 3 x 2 matrix
G

 [3 4]
 [5 6]]
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Matrices in numpy
 Getting Diagonal Elements of a Matrix
 To retrieve the diagonal elements of a matrix, we can use diagonal() function as:
 a = diagonal(matrix)
 The diagonal() function returns a 1D array that contains diagonal elements of the
original matrix. To understand this function, we can take an example.
 a = matrix('1 2 3; 4 5 6; 7 8 9')

h
ec
 print(a)

.T
 O/P [[1 2 3] # create a 3 x 3 matrix

B
 [4 5 6]

E) T
 [7 8 9]]
 Consider the following code:S& FE
(C LS
 d = diagonal(a)
G

 print(d)
 O/P: [1 5 9] #this is the diagonal
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Matrices in numpy
 The reshape() Function
 This function is useful to convert a 1D array into a multidimensional (2D or 3D)
array. The syntax of writing this function is: reshape(arrayname, (n, r, c))
 Here, ‘arrayname’ represents the name of the array whose elements to be
converted. ‘n’ indicates the number of arrays in the resultant array.
 ‘r’ , ‘c’ indicates the number of rows and columns, respectively.

h
ec
 a = array([1, 2, 3, 4, 5, 6])

.T
 To convert ‘a’ into a 2D array using the reshape() function, we can write:

B
E) T
 b = reshape(a, (2, 3))
 O/P: [[1 2 3] S& FE
(C LS
 [4 5 6] ]
G

 Observe the starting two pairs of square brackets which indicate that it is a 2D
array.
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Matrices in numpy
 The reshape() Function
 b = reshape(a, (3, 2))
 O/P: [[1 2]
 [3 4]
 [5 6] ]
 To convert this 1D array into a 3D array, we can use the reshape() function as:

h
 b = reshape(a, (2, 3, 2))

ec
 They represent that 2 arrays each with 3 rows and 2 columns.

.T
 [[[ 0 1]

B
 [ 2 3]

E) T
S& FE
 [ 4 5]]
 [[ 6 7]
(C LS
 [ 8 9]
G

 [10 11]] ]
 b = reshape(a, (3, 2, 2)) ans??
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Task for Matrices in numpy
1. Create the following matrices using [Link]():
 A 2×2 matrix:
 A 3×3 identity matrix.
 A 3×2 matrix with random integers between 1 and 20.

2. Create a 1D NumPy array with values from 1 to 12.

h
ec
 Use the reshape() function to convert it into:

.T
B
 A 3 × 4 matrix

E) T
 A 4 × 3 matrix
 A 2 × 2 × 3 3D array S& FE
(C LS
 Print all the reshaped arrays with proper labels.
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Matrix Addition and Multiplication
 We can use arithmetic operators like +, - and / to perform addition, subtraction
division and multiplication operations on 2 matrices.
 import numpy as np
 # create matrices
 a = [Link]('1 2 3; 4 5 6') # size 2 x 3
 b = [Link]('2 2 2; 1 -1 2') # size 2 x 3
 print("Matrix a:\n", a)

h
 print("Matrix b:\n", b)

ec
 c=a+b # addition

.T
 print("a + b:\n", c)

B
 c=a-b # substraction

E) T
S& FE
 print("a - b:\n", c)
 d = [Link](a, b) # element-wise division
(C LS
 print("a / b (element-wise):\n", d)
G

 e = [Link](a, b) # element-wise multiplication


 print("a * b (element-wise):\n", e)
 print("Transpose of Array a:\n", a.T) Transpose of a matrix
Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )
FET – [Link] (CS & E)
Task for Matrices Arithmetic Operations
 Create a matrix (3X2)
 Matrix addition
 Matrix subtraction
 Element-wise multiplication
 Element-wise division

h
ec
 Transpose of a matrix

.T
B
E) T
S& FE
(C LS
G

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )


FET – [Link] (CS & E)
Matrix Addition and Multiplication
 Matrix a:
 [[1 2 3]
 [4 5 6]]
a * b (element-wise):
 Matrix b: [[ 2 4 6]
 [[ 2 2 2] [ 4 -5 12]]
 [ 1 -1 2]]

h
 a + b:

ec
 [[3 4 5]

.T
 [5 4 8]]

B
 a - b:

E) T
S& FE
 [[-1 0 1]
 [ 3 6 4]]
(C LS
 a / b (element-wise):
G

 [[ 0.5 1. 1.5]
 [ 4. -5. 3. ]]

Prepared by : Dr. Tejas Bhatt Subject : Computer Programming Paradigm (Python )

You might also like