2.1 The Array Structure
2.1 The Array Structure
Array is a container which can hold a fix number of items and these items should be of the
same type. Most of the data structures make use of arrays to implement their algorithms.
Following are the important terms to understand the concept of Array.
Typecodes are used to define the type of value the array will hold. Below is a table of Typecodes.
Typecode Value
Sample Code: The code below displays all the elements in an array. The for loop is used to
display all the elements in an array. The ‘i’ is the typecode for integer.
for x in array1:
print(x)
Sample Code: In the example, element in index 0 and index 2 are accessed.
print (array1[0])
print (array1[2])
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. The
buil-in insert() method is used.
array1.insert(1,60)
for x in array1:
print(x)
Deletion refers to removing an existing element from the array and re-organizing all
elements of an array. The python built-in remove() method is used.
Sample Code: In the code example, we remove the element 40 from an array.
from array import *
array1.remove(40)
for x in array1:
print(x)
The search for an array element can be performed using its index or its value.
Sample Code: In the example code, the index of an element 40 is returned. If the value is not
present in the array then program returns error.
print (array1.index(40))
This refers to updating an existing element from the array at a given index.
Sample Code: In the example code, the element in index 2 is updated with a new value of 80
array1[2] = 80
for x in array1:
print(x)