Array
Practice Questions
Arrays in Python
Arrays in Python:Arrays are not all popular in python , unlike other programming languages such as C++ and Java which are static arrays.
Array can be created in Python by importing an array module/Library to the python program. 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.
The basic operations supported by an array are
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 indexInsert () 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 the 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])
array1.insert(1,60) #(1,60)here 1 is the index position of the
element to insert the value 60
for x in array1:
print(x)
When we compile and execute the above program:
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])
array1.remove(40)
for x in array1:
print(x)
When we compile and execute the above program, it produces the following result which shows the element is removed from the array.
Output
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 (array1.index(40))
When we compile and execute the above program, it produces the following result which shows the index of the element. If the value is not present in the array then the program returns an error.
Output
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 # here 2 is the index value of the element and 80
is the value to update in [2]
for x in array1:
print(x)
When we compile and execute the above program, it produces the following result which shows the new value at the index position 2.
Output