Python Array Basics and Usage Guide
Python Array Basics and Usage Guide
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
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
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
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
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
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
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
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
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
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
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
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.
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
# 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
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
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
h
ec
.T
B
E) T
S& FE
(C LS
G
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
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
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
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
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
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.
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
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
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
h
ec
5. Using zeros() and ones() functions
.T
B
E) T
S& FE
(C LS
G
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
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
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
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
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
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
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
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
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
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
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]
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. ].
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
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
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
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
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
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
h
ec
.T
B
E) T
S& FE
(C LS
G
h
ec
.T
B
E) T
S& FE
(C LS
G
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
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
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
h
ec
.T
B
E) T
S& FE
(C LS
G
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
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
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
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
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
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
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
h
ec
.T
B
E) T
S& FE
(C LS
G
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
h
ec
.T
B
E) T
S& FE
(C LS
G
h
ec
.T
B
E) T
S& FE
(C LS
G
h
ec
Reverse the array
.T
B
E) T
S& FE
(C LS
G
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
h
ec
[ [[1 2 3]
.T
[4 5 6]]
B
E) T
[[1 1 1]
[1 0 1]] ] S& FE
(C LS
G
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
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.
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
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
h
ec
Transpose of a matrix
.T
B
E) T
S& FE
(C LS
G
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. ]]