UNIT-IV
Arrays:An array is defined as a collection of items that are stored at
contiguous memory locations. It is a container which can hold a fixed
number of items, and these items should be of the same type. An array is
popular in most programming languages like C/C++, JavaScript, etc.
The array can be handled in Python by a module named array. It is
useful when we have to manipulate only specific data values.
Following are the terms to understand the concept of an array:
Element - Each item stored in an array is called an element.
Index - The location of an element in an array has a numerical index,
which is used to identify the position of the element.
Array Representation: An array can be declared in various ways and
different languages. The important points that should be considered
are as follows:
o Index starts with 0.
o We can access each element via its index.
o The length of the array defines the capacity to store the
elements.
Basic Operations: Following are the basic operations supported by an array.
Traverse − print all the array elements one by one.
Insertion − Adds an element at the given index.
Deletion − Deletes an element at the given index.
Search − Searches an element using the given index or by the value.
Update − Updates an element at the given index.
Creating an Array: Array is created in Python by importing array module to the python
program. Then the array is declared as shown below:
from array import *
arrayName = array(typecode, [Initializers])
Typecode are the codes that are used to define the type of value the array will hold.
Some common typecodes used are:
Typecode Value
b Represents signed integer of size 1 byte
B Represents unsigned integer of size 1 byte
c Represents character of size 1 byte
i Represents signed integer of size 2 bytes
I Represents unsigned integer of size 2 bytes
f Represents floating point of size 4 bytes
d Represents floating point of size 8 bytes
Before looking at various array operations lets create and print an array using
python.
The below code creates an array named array1.
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
Output:
10
20
30
40
50
Accessing Array Element
We can access each element of an array using the index of the element.
from array import*
array1 =array('i',[10,20,30,40,50])
print(array1[0])
print(array1[2])
Output:
10
30
Insertion Operation: Insert operation is to insert one or more data elements into
an array. Based on the requirement, a new element can be added at the
beginning, end, or any given index of array.
Here, we add a data element at the middle of the array using the python in-built
insert() method.
from array import*
array1 =array('i',[10,20,30,40,50])
[Link](1,60)
for x in array1:
print(x)
When we compile and execute the above program, it produces the following
result which shows the element is inserted at index position 1.
Output
10
60
20
30
40
50
Deletion Operation: Deletion refers to removing an existing element
from the array and re-organizing all elements of an array.
Here, we remove a data element at the middle of the array using the python in-
built remove() method.
from array import*
array1 =array('i',[10,20,30,40,50])
[Link](40)
for x in array1:
print(x)
Output
10
20
30
50
Search Operation
You can perform a search for an array element based on its value or its index.
Here, we search a data element using the python in-built index() method.
from array import*
array1 =array('i',[10,20,30,40,50])
print([Link](40))
Output
3
Update Operation
Update operation refers to updating an existing element from the array at a
given index.
Here, we simply reassign a new value to the desired index we want to update.
from array import*
array1 =array('i',[10,20,30,40,50])
array1[2]=80
for x in array1:
print(x)
Output
10
20
80
40
50
Advantages of Arrays
The following are some advantages of arrays:
a. 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.
b. The size of the array is not fixed in Python. Hence, we need not specify
how many elements we are going to store into an array in the beginning.
c. Arrays can grow or shrink in memory dynamically (during runtime).
d. Arrays are useful to handle a collection of elements like a group of
numbers or characters.
e. Methods that are useful to process the elements of any array are
available in 'array' module.
Array Module of Python
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
When we import the array module, we are able to get the 'array' class of that
module that helps us to create an array. See the following example:
a =[Link]('i',[4,6,2,9])
Here, the first 'array' represents the module name and the next 'array'
represents the class name for which the object is created. We should
understand that we are creating our array as an object of array class.
The second way of importing the array module is to give it an alias name, as:
import array as ar
Here, the array is imported with an alternate name 'ar'. Hence we can refer to
the array class of 'ar' module as:
a =[Link]('i', [4,6,2,9])
The third way of importing the array module is to write:
from array import *
Observe the '*' symbol that represents 'all'. The meaning of this statement is
this: import all (classes, objects, variables etc) from the array module into our
program. 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. We can create the array as:
a =array('i',[4,6,2,9])
Python program to create an integer type array.
import array
a = [Link]('i', [5, 6, -7, 8])
print('The array elements are:')
for element in a:
print(element)
Python program to create an integer type array.
from array import *
a = array('i', [5, 6, -7, 8])
print('The array elements are:')
for element in a:
print(element)
A Python program to create an array with a group of characters.
from array import *
arr = array('u', ['a','b','c','d','e'])
print('The array elements are:')
for ch in arr:
print(ch)
Array Types in Pythons
Till now, we got good idea on arrays in Python. When talking about arrays, any
programming language like C or Java offers two types of arrays. They are:
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.
Multi-dimensional arrays: These arrays represent more than one row and
more than one column of elements. For example, marks obtained by 3 students
each one in 5 subjects can be written as 'marks' array as:
marks = [[50, 60, 70, 66, 72], [60, 62, 71, 56, 70], [55, 59, 80, 68, 65]]
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-dimensional array.
marks =[[50, 60, 70, 66, 72],
[60, 62, 71, 56, 70],
[55, 59, 80, 68, 65]]
Each row of the above array can be again represented as a single dimensional
array. Thus the above array contains 3 single dimensional arrays. Hence, it is
called a two dimensional array. A two dimensional array is a combination of
several single dimensional arrays. Similarly, a three dimensional array is a
combination of several two dimensional 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. We can construct
multidimensional arrays using third party packages like numpy (numerical
python).
Arrays using zeros() and ones()
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)
where ‘n’ represents the number of elements. we can eliminate the ‘datatype’
argument. If we do not specify the ‘datatype’, then the default datatype used
by numpy is ‘float’. See the examples:
zeros(5)
This will create an array with 5 elements all are zeros, as: [0. 0. 0. 0. 0.]. If we
want this array in integer format, we can use ‘int’ as datatype, as:
zeros(5, int)
this will create an array as: [0 0 0 0 0].
If we use ones() function, it will create an array with all elements 1. For example,
ones(5, float)
will create an array with 5 integer elements all are 1s as: [1. 1. 1. 1. 1.].
A Python program to create arrays using zeros() and ones().
from numpy import *
a = zeros(5, int)
print(a)
b = ones(5)
#default datatype is float
print(b)
from numpy import *
a = zeros(7)
print(a)
b = ones(6,int)
print(b)
Viewing and Copying Arrays
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. If the newly created array is modified, the original array will also be
modified since the elements in both the arrays will be like mirror images.
from numpy import *
a = arange(1, 6)
b = [Link]()
print('Original array:', a)
print('New array:', b)
b[0]=99
print('After modification:')
print('Original array:', a)
print('New array:', b)
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 of an
existing array and its elements. When the newly created array is modified, it will
not affect the existing array or vice versa.
Python Multi-dimensional Arrays
The 2D arrays, 3D arrays etc. are called multi-dimensional arrays. A 2D array
contains more than 1 row and 1 column and it can be treated as a combination
of several 1D arrays. A 2D array is also considered as a matrix. For example, a
2D array with ‘m’ rows and ‘n’ columns is called m x n matrix.
We can create multi-dimensional arrays in the following ways:
Using array() function
Using ones() and zeroes() functions
Using eye() function
Using reshape() function
The array() Function
Numpy’sarray() function can be used to create a multidimensional array.
Usually, we pass lists of elements to this function. If we pass one list of
elements to this function, then it will create a 1D array. If we pass two lists of
elements, then this function creates a 2D array.
a = array([1,2,3,4])
a = array([[1,2,3,4], [5,6,7,8]])
Displaying of 2D array elements
[[1 2 3 4]
[5 6 7 8]]
Even though the elements are displayed in 2 rows and 4 columns, the internal
memory allocated to all these elements would be in the form of a single
rowcontaining 8 blocks (2 x 4 = 8). The elements are stored in the contiguous
memory locations as shown below.
The ones() and zeros() Functions
The ones() function is useful to create a 2D array with several rows and columns
where all the elements will be taken as 1. The format of this function is:
ones((r, c), dtype)
Here, ‘r’ represents the number of rows and ‘c’ represents the number of
columns. ‘dtype’ represents the datatype of the elements in the array. For
example,
a = ones((3, 4), float)
will create a 2D array with 3 rows and 4 columns and the datatype is taken as
float. we can see the array as:
[[1. 1.1. 1.]
[1. 1.1. 1.]
[1. 1.1. 1.]]
Just like the ones() function, we can also use the zeros() function to create a 2D
array with elements filled with zeros.
b = zeros((3,4), int)
Then a 2D array with 2 rows and 4 columns will be created where all elements
will be 0s, as shown below:
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
The eye() Function
The eye() function creates a 2D array and fills the elements in the diagonal
with 1s. The general format of using this function is:
eye(n, dtype=datatype)
This will create an array with ‘n’ rows and ‘n’ columns. The default datatype is
‘float’. For example, eye(3) will create a 3x3 array and fills the diagonal elements
with 1s as shown below:
b =eye(3)
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
from numpy import *
b =eye(4)
print(b)
The reshape() Function
The reshape() function has been already discussed in the previous section. We
will have an elaborate discussion about this function now. 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. For example, we
take a 1D array ‘a’ with 6 elements as:
a = array([1, 2, 3, 4, 5, 6])
To convert ‘a’ into a 2D array using the reshape() function, we can write:
b = reshape(a, (2, 3))
We are converting the elements of the array ‘a’ into a 2D array with 2 rows and
3 columns, and the resultant array is ‘b’. So, the 2D array ‘b’ looks like this:
[[1 2 3]
[4 5 6]]
Observe the starting two pairs of square brackets which indicate that it is a 2D
array. Suppose, we write:
b = reshape(a, (3, 2))
This will convert ‘a’ into a 2D array with 3 rows and 2 columns that looks like
this:
[[1 2]
[3 4]
[5 6]]
It is possible to use the reshape() function to convert a 1D array into a 3D
array. Let’s take a 1D array ‘a’ with 12 elements as:
a = arange(12)
[0 1 2 3 4 5 6 7 8 9 10 11]
Now, to convert this 1D array into a 3D array, we can use the reshape() function
as:
b = reshape(a, (2, 3, 2))
b = reshape(a, (2, 3, 2))
Here, ‘a’ represents the arraynamethat is being converted. In the reshape()
function, after ‘a’, observe the figures (2, 3, 2). They represent that we want 2
arrays each with 3 rows and 2 columns. So, the resultant 3D array ‘b’ looks
like this:
[ [ [ 0 1]
[ 2 3]
[ 4 5] ]
[ [ 6 7]
[ 8 9]
[10 11] ] ]
So, ‘b’ is a 3D array of size 2x3x2. Suppose, we write:
b = reshape(a, (3, 2, 2))
[ [ [ 0 1]
[ 2 3] ]
[ [ 4 5]
[ 6 7] ]
[ [ 8 9]
[10 11] ] ]