Water Industry Process Automation & Control Monthly - April 2024
Arrays in python
1. Arrays in Python
February 13, 2018
1 Array
• Collection of homogeneous values
• Used to implement other data structures such as stacks, queues, linked lists etc...
• One of the common application is Processing of matrices.
• In Python,arrays are not fundamental data type
• To use arrays, user needs to
– import the array module
– import numpy module
1.1 Importing Array Module
In [1]: from array import *
1.1.1 Declaring Arrays
arrayname = array(typecode, [list of elements])
In [3]: d = array('u',['h','e','l','l','o'])
print(d)
array('u', 'hello')
1.1.2 Creating Array
In [2]: from array import *
my_array = array('i',[11,21,31,41])
print("Display the array :",my_array)
print()
print("Array Elements :",end='')
for i in my_array:
print(i,end=' ')
Display the array : array('i', [11, 21, 31, 41])
Array Elements :11 21 31 41
1
2. 1.1.3 Reading input from the user as a list of integers
In [4]: list_input = [int(x) for x in input("Enter array elements : ").strip().split(' ')]
print()
print("Entered elements :", list_input)
print()
my_array2 = array('i', list_input)
print("Display the array :",my_array2)
print()
Enter array elements : 11 12 13
Entered elements : [11, 12, 13]
Display the array : array('i', [11, 12, 13])
1.1.4 Accessing an element of an array
In [7]: print("First element : %d" % my_array[0])
size = len(my_array)
print("Sum of first and last element : %d" % (my_array[0]+my_array[size-1]))
First element : 11
Sum of first and last element : 52
1.1.5 len(arrayname)
• Number of elements in an Array
In [8]: size = len(my_array)
print("No. of elements : %d" % size)
No. of elements : 4
1.1.6 array.insert(pos,item)
• Adding element in the middle of the array
In [9]: size = len(my_array2)
mid = int(size/2)
print("index of middle element : %d"% mid)
print()
2
3. x = int(input("Enter the value to be inserted in the middle :").strip())
print()
print("Before insert(pos,item) :", my_array2)
print()
my_array2.insert(mid,x)
print("Before insert(pos,item) :", my_array2)
index of middle element : 1
Enter the value to be inserted in the middle :55
Before insert(pos,item) : array('i', [11, 12, 13])
Before insert(pos,item) : array('i', [11, 55, 12, 13])
1.1.7 array.append(item)
• Adding new element to the end of the array
In [10]: y = int(input("Enter the value to be added to the end :").strip())
print()
print("Before append(item) :", my_array2)
print()
my_array2.append(y)
print("After append(item) :", my_array2)
Enter the value to be added to the end :99
Before append(item) : array('i', [11, 55, 12, 13])
After append(item) : array('i', [11, 55, 12, 13, 99])
1.1.8 array.extend(array2)
• Extending the existing array from another array
In [11]: print("Before extend(array2) :", my_array)
print()
my_array.extend(my_array2)
print("Extended array:", my_array)
3
4. Before extend(array2) : array('i', [11, 21, 31, 41])
Extended array: array('i', [11, 21, 31, 41, 11, 55, 12, 13, 99])
1.1.9 array.fromlist(list)
• Extending an array from list
In [ ]: print("Before fromlist(list) :", my_array)
print()
new_list = [int(x) for x in input('Enter elements comma separated: ').strip().split(',')
print()
my_array.fromlist(new_list)
print("Extended Array from list :",my_array)
Before fromlist(list) : [[11 23]
[33 44]]
1.1.10 array.typecode
• Print typecode of the array
In [14]: print(my_array.typecode)
i
1.1.11 array.itemsize
• Print length of one array item in bytes
In [15]: print("Item size : %d bytes" % my_array.itemsize)
Item size : 4 bytes
1.1.12 array.byteswap()
• Swaps the characters bytewise
In [16]: print('before byteswap() : ', my_array)
print()
my_array.byteswap()
4
5. print('after byteswap() : ',my_array)
print()
# Repeat byteswap to retrieve the original array
my_array.byteswap()
print('after byteswap() called twice : ',my_array)
before byteswap() : array('i', [11, 21, 31, 41, 11, 55, 12, 13, 99, 1, 2])
after byteswap() : array('i', [184549376, 352321536, 520093696, 687865856, 184549376, 922746880
after byteswap() called twice : array('i', [11, 21, 31, 41, 11, 55, 12, 13, 99, 1, 2])
1.1.13 array.count(item)
• Occurance of a item in array
In [17]: my_array.count(21)
Out[17]: 1
1.1.14 array.pop(index)
• Deleting element
In [18]: print("Before pop(index): ",my_array)
print()
#Pop element @ index,i from the array using array.pop(index)
my_array.pop(2)
print("After pop(index): ",my_array)
print()
#Pop last element using array.pop()
my_array.pop()
print("After pop(): ",my_array)
Before pop(index): array('i', [11, 21, 31, 41, 11, 55, 12, 13, 99, 1, 2])
After pop(index): array('i', [11, 21, 41, 11, 55, 12, 13, 99, 1, 2])
After pop(): array('i', [11, 21, 41, 11, 55, 12, 13, 99, 1])
5
6. 1.1.15 array.reverse()
• Reverse an array
In [19]: print("Before reveral: ",my_array)
print()
my_array.reverse()
print("After reveral: ",my_array)
Before reveral: array('i', [11, 21, 41, 11, 55, 12, 13, 99, 1])
After reveral: array('i', [1, 99, 13, 12, 55, 11, 41, 21, 11])
1.1.16 array.remove(item)
• Remove the first occurance of an item from the array
In [20]: print("Before remove(x) :", my_array)
print()
x = int(input("Enter the item to be removed ").strip())
if x in my_array:
my_array.remove(x)
print("After removal :", my_array)
else:
print("Item not in array")
Before remove(x) : array('i', [1, 99, 13, 12, 55, 11, 41, 21, 11])
Enter the item to be removed 55
After removal : array('i', [1, 99, 13, 12, 11, 41, 21, 11])
1.1.17 array.tolist()
• Creating a list from array
In [21]: print("Array before tolist() :", my_array)
print()
l = my_array.tolist()
print("Array after tolist() ", my_array)
print()
print("Created list : ", l)
6
7. Array before tolist() : array('i', [1, 99, 13, 12, 11, 41, 21, 11])
Array after tolist() array('i', [1, 99, 13, 12, 11, 41, 21, 11])
Created list : [1, 99, 13, 12, 11, 41, 21, 11]
1.2 Using NumPy module
• Numeric / Numerical Python
• Full fledge Python package
• Contains objects of multidimensional array and routines for processing them.
• Advantages of Python with NumPy
1. Efficient computation of multi-dimensional arrays
2. Fast precompiled functions for mathematical and numerical routines
3. NumPy is designed for scientific computation
1.2.1 array() in NumPy
• Creating ndarray objects
In [22]: import numpy as np
arr = np.array([1,2,3,4])
print('Array 1 : ',arr)
print('datatype : ',arr.dtype)
print()
arr2 = np.array([1.,2,3,4])
print('Array 2 : ',arr2)
print('datatype : ',arr2.dtype)
print()
Array 1 : [1 2 3 4]
datatype : int64
Array 2 : [ 1. 2. 3. 4.]
datatype : float64
Program : Convert Celsius to Farenheit
In [23]: import numpy as np
c_array = np.array([21.3,54.1,36.2,45.6])
print("Celsius values : ", c_array)
print()
7
11. [[21 22 23 24]
[31 32 33 34]]
• using ellipsis(...)
– for making tuple selection of the same length as array dimension
In [31]: import numpy as np
x = np.matrix('11,12,13,14;21,22,23,24;31,32,33,34;41,42,43,44')
print(' Original Matrix')
print(x)
print()
#Column selection
print('Column 1 selection :')
print(x[...,1])
print()
#Column slicing
print('Slicing from Column 1 onwards :')
print(x[...,1:])
print()
#Row Selection
print('Row 1 selection :')
print(x[1,...])
Original Matrix
[[11 12 13 14]
[21 22 23 24]
[31 32 33 34]
[41 42 43 44]]
Column 1 selection :
[[12]
[22]
[32]
[42]]
Slicing from Column 1 onwards :
[[12 13 14]
[22 23 24]
[32 33 34]
[42 43 44]]
Row 1 selection :
[[21 22 23 24]]
11
12. 1.2.6 Advanced indexing
• Two kinds
1. Integer Indexing
– based on N Dimensional index
– any arbitrary element in an array can be selected
2. Boolean Indexing
– used when the result is meant to be the result of boolean operations
Integer Indexing
In [32]: import numpy as np
a = np.matrix('1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16')
print('Original Matrix')
print(a)
print()
# row contains row indices and col contains column indices for elements in the corners
row = np.array([[0,0],[3,3]])
col = np.array([[0,3],[0,3]])
# row and col indices are combined to form a new ndarray object
b = a[row,col]
print(b)
print()
# row contains row indices and col contains column indices for elements in the middle
row1 = np.array([[1,1],[2,2]])
col1 = np.array([[1,2],[1,2]])
# row and col indices are combined to form a new ndarray object
b1 = a[row1,col1]
print(b1)
print()
# row contains row indices and col contains column indices for elements in the middle e
row2 = np.array([[1,1],[2,2]])
col2 = np.array([[0,3],[0,3]])
# row and col indices are combined to form a new ndarray object
b2 = a[row2,col2]
print(b2)
Original Matrix
[[ 1 2 3 4]
12