Arrays in Python
Arrays in Python
Unlike other programming languages like C++ or Java, Python does not have built-in
support for arrays. However, Python has several data types like lists and tuples
(especially lists) that are often used as arrays but, items stored in these types of
sequences need not be of the same type.
In addition, we can create and manipulate arrays the using the array module. Before
proceeding further, let's understand arrays in general.
These elements are stored at contiguous memory location. Each location of an element in
an array has a numerical index starting from 0. These indices are used to identify and
access the elements.
Array Representation
Arrays are represented as a collection of multiple containers where each container stores
one element. These containers are indexed from '0' to 'n-1', where n is the size of that
particular array.
1
As per the above illustration, following are the important points to be considered −
The array() function accepts typecode and initializer as a parameter value and returns an
object of array class.
Syntax
The syntax for creating an array in Python is −
# importing
import array as array_name
# creating array
obj = array_name.array(typecode[, initializer])
Where,
typecode − The typecode character used to speccify the type of elements in the
array.
initializer − It is an optional value from which array is initialized. It must be a list,
a bytes-like object, or iterable elements of the appropriate type.
Example
The following example shows how to create an array in Python using the array module.
Open Compiler
import array as arr
2
# creating an array with float type
a = [Link]('d', [1.1, 2.2, 3.3])
print (type(a), a)
Python array type is decided by a single character Typecode argument. The type codes
and the intended data type of array is listed below −
Example
The below code shows how to access elements of an array.
Open Compiler
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])
When we compile and execute the above program, it produces the following result −
10
30
Insertion Operation
In insertion operation, we 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.
Example
Here, we add a data element at the middle of the array using the python in-built insert()
method.
Open Compiler
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.
10
60
20
30
40
50
4
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.
Open Compiler
from array import *
array1 = array('i', [10,20,30,40,50])
[Link](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 form the array.
10
20
30
50
Search Operation
You can perform a search operation on an array to find an array element based on its
value or its index.
Example
Here, we search a data element using the python in-built index() method −
Open Compiler
from array import *
array1 = array('i', [10,20,30,40,50])
print ([Link](40))
When we compile and execute the above program, it will display the index of the
searched element. If the value is not present in the array, it will return an error.
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.
5
Example
In this example, we are updating the value of array element at index 2.
Open Compiler
from array import *
array1 = array('i', [10,20,30,40,50])
array1[2] = 80
for x in array1:
print(x)
On executing the above program, it produces the following result which shows the new
value at the index position 2.
10
20
80
40
50
Accessing an array items in Python refers to the process of retrieving the value stored at
a specific index in the given array. Here, index is an numerical value that indicates the
location of array items. Thus, you can use this index to access elements of an array in
Python.
An array is a container that holds a fix number of items of the same type. Python
uses array module to achieve the functionality like an array.
Using indexing
Using iteration
Using enumerate() function
Using indexing
The process of accessing elements of an array through the index is known as Indexing.
In this process, we simply need to pass the index number inside the index operator []. The
index of an array in Python starts with 0 which means you can find its first element at
index 0 and the last at one less than the length of given array.
Example
The following example shows how to access elements of an array using indexing.
6
Open Compiler
import array as arr
# creating array
numericArray = [Link]('i', [111, 211, 311, 411, 511])
#indexing
print (numericArray[0])
print (numericArray[1])
print (numericArray[2])
When you run the above code, it will show the following output −
111
211
311
Using iteration
In this approach, a block of code is executed repeatedely using loops such as for and
while. It is used when you want to access array elements one by one.
Example
In the below code, we use the for loop to access all the elements of the specified array.
Open Compiler
import array as arr
# creating array
numericArray = [Link]('i', [111, 211, 311, 411, 511])
111
211
311
411
511
ACCESS ARRAY ITEMS
7
Using enumerate() function
The enumerate() function can be used to access elements of an array. It accepts an array
and an optional starting index as parameter values and returns the array items by
iterating.
Example
In the below example, we will see how to use the enumerate() function to access array
items.
Open Compiler
import array as arr
# creating array
numericArray = [Link]('i', [111, 211, 311, 411, 511])
This operation is implemented using multiple formats, which are listed below −
Use the [:index] format to access elements from beginning to desired range.
To access array items from end, use [:-index] format.
Use the [index:] format to access array items from specific index number till the
end.
Use the [start index : end index] to slice the array elements within a range. You can
also pass an optional argument after end index to determine the increment
between each index.
Example
The following example demonstrates the slicing operation in Python.
8
Open Compiler
import array as arr
# creating array
numericArray = [Link]('i', [111, 211, 311, 411, 511])
# slicing operation
print (numericArray[2:])
print (numericArray[0:3])
Python array is a mutable sequence which means they can be changed or modified
whenever required. However, items of same data type can be added to an array. In the
similar way, you can only join two arrays of the same data type.
Python does not have built-in support for arrays, it uses array module to achieve the
functionality like an array.
Syntax
Syntax of the append() method is as follows −
append(v)
Where,
v − new value is added at the end of the array. The new value must be of the same
type as datatype argument used while declaring array object.
9
Example
Here, we are adding element at the end of specified array using append() method.
Open Compiler
import array as arr
a = [Link]('i', [1, 2, 3])
[Link](10)
print (a)
Syntax
Syntax of this method is shown below −
insert(i, v)
Where,
Example
The following example shows how to add array elements at specific index with the help of
insert() method.
Open Compiler
import array as arr
a = [Link]('i', [1, 2, 3])
[Link](1,20)
print (a)
Syntax
This method has the following syntax −
extend(x)
Where,
Example
In this example, we are adding items from another array to the specified array.
Open Compiler
import array as arr
a = [Link]('i', [1, 2, 3, 4, 5])
b = [Link]('i', [6,7,8,9,10])
[Link](b)
print (a)
The array module defines two methods namely remove() and pop(). The remove() method
removes the element by value whereas the pop() method removes array item by its
position.
Python does not provide built-in support for arrays, however, we can use the array
module to achieve the functionality like an array.
11
Syntax
[Link](v)
Example
The below example shows the usage of remove() method. Here, we are removing an
element from the specified array.
Open Compiler
import array as arr
# creating array
numericArray = [Link]('i', [111, 211, 311, 411, 511])
Syntax
[Link](i)
Example
In this example, we will see how to use pop() method to remove elements from an array.
Open Compiler
12
import array as arr
# creating array
numericArray = [Link]('i', [111, 211, 311, 411, 511])
LOOP ARRAYS
Loops are used to repeatedly execute a block of code. In Python, there are two types of
loops named for loop and while loop. Since the array object behaves like a sequence, you
can iterate through its elements with the help of loops.
The reason for looping through arrays is to perform operations such as accessing,
modifying, searching, or aggregating elements of the array.
Example
The below example demonstrates how to iterate over an array using the "for" loop −
Open Compiler
import array as arr
newArray = [Link]('i', [56, 42, 23, 85, 45])
for iterate in newArray:
print (iterate)
56
13
42
23
85
45
Example
The following example shows how you can loop through an array using a while loop −
Open Compiler
import array as arr
# creating array
a = [Link]('i', [96, 26, 56, 76, 46])
# loop variable
idx = 0
# while loop
while idx < l:
print (a[idx])
# incrementing the while loop
idx+=1
96
26
56
76
46
Example
The code below illustrates how to use for loop with array index.
Open Compiler
import array as arr
a = [Link]('d', [56, 42, 23, 85, 45])
l = len(a)
for x in range(l):
print (a[x])
56.0
42.0
23.0
85.0
45.0
COPPY ARRAYS
In Python, copying an array refers to the process of creating a new array that contains all
the elements of the original array. This operation can be done using assignment operator
(=) and deepcopy() method. In this chapter, we discuss how to copy an array object to
another. But, before getting into the details let's breifly discuss arrays.
Python's built-in sequence types i.e. list, tuple, and string are indexed collection of items.
However, unlike arrays in C/C++, Java etc. they are not homogenous, in the sense the
elements in these types of collection may be of different types. Python's array module
helps you to create object similar to Java like arrays.
Python arrays can be of string, integer or float type. The array class constructor is used as
follows −
import array
obj = [Link](typecode[, initializer])
Where, the typecode may be a character constant representing the data type.
15
Example
In the following example, we are using assignment operator to copy array in Python.
Open Compiler
import array as arr
a = [Link]('i', [110, 220, 330, 440, 550])
b=a
print("Copied array:",b)
print (id(a), id(b))
Check the id() of both a and b. Same value of id confirms that simple assignment doesn't
create a copy. Since "a" and "b" refer to the same array object, any change in the array
"a" will reflect in "b" too −
a[2] = 10
print (a,b)
array('i', [110, 220, 10, 440, 550]) array('i', [110, 220, 10, 440, 550])
Example
The following example demonstrates how to copy array in Python −
Open Compiler
import array as arr
import copy
a = [Link]('i', [110, 220, 330, 440, 550])
b = [Link](a)
print("Copied array:",b)
16
Copied array: array('i', [110, 220, 330, 440, 550])
Now check the id() of both "a" and "b". You will find the ids are different.
2771967069936 2771967068976
This proves that a new object "b" is created which is an actual copy of "a". If we change
an element in "a", it is not reflected in "b".
a[2]=10
print (a,b)
array('i', [110, 220, 10, 440, 550]) array('i', [110, 220, 330, 440, 550])
REVERSE ARRAYS
Reversing an array is the operation of rearranging the array elements in the opposite
order. There are various methods and approaches to reverse an array in Python including
reverse() and reversed() methods.
In Python, array is not one of the built-in data types. However, Python's standard library
has array module which helps us to create a homogenous collection of string, integer or
float types.
17
Using slicing operation
Slicing operation is the process of extracting a part of array within the specified
indices. In Python, if we use the slice operation in the form [::-1] then, it will display a
new array by reversing the original one.
In this process, the interpreter starts from the end and stepping backwards by 1 until it
reaches the beginning of the array. As a result, we get a reverse copy of original array.
Example
The below example demonstrates how to use the slicing operation to reverse an array in
Python.
Open Compiler
import array as arr
# creating array
numericArray = [Link]('i', [88, 99, 77, 55, 66])
When you run the code, it will produce the following output −
Since reverse() is a method of list class, we cannot directly use it to reverse an array
created through the Python array module. We have to first transfer the contents of an
array to a list with tolist() method of array class, then we call the reverse() method
and at the end, when we convert the list back to an array, we get the array with reversed
order.
Example
Here, we will see the use of reverse() method in reversing an array in Python.
Open Compiler
import array as arr
18
# creating an array
numericArray = [Link]('i', [10,5,15,4,6,20,9])
print("Array before reversing:", numericArray)
Example
In this example, we are using the reversed() method to reverse an array in Python.
Open Compiler
import array as arr
# creating an array
numericArray = [Link]('i', [12, 10, 14, 16, 20, 18])
print("Array before reversing:", numericArray)
Example
The following example shows how to reverse an array in Python using for loop.
Open Compiler
import array as arr
a = [Link]('i', [10,5,15,4,6,20,9])
b = [Link]('i')
for i in range(len(a)-1, -1, -1):
[Link](a[i])
print(a)
print(b)
SORT ARRAY
Python's array module defines the array class. An object of array class is similar to the
array as present in Java or C/C++. Unlike the built-in Python sequences, array is a
homogenous collection of either strings, or integers, or float objects.
The array class doesn't have any function/method to give a sorted arrangement of its
elements. However, we can achieve it with one of the following approaches −
20
Sort Arrays Using a Sorting Algorithm
We implement the classical bubble sort algorithm to obtain the sorted array. To do it,
we use two nested loops and swap the elements for rearranging in sorted order.
Example
Run the following code using a Python code editor −
Open Compiler
import array as arr
a = [Link]('i', [10,5,15,4,6,20,9])
for i in range(0, len(a)):
for j in range(i+1, len(a)):
if(a[i] > a[j]):
temp = a[i];
a[i] = a[j];
a[j] = temp;
print (a)
First, declare an array and obtain a list object from it, using tolist() method. Then, use
the sort() method to get a sorted list. Lastly, create another array using the sorted list
which will display a sorted array.
Example
The following code shows how to get sorted array using the sort() method.
Open Compiler
import array as arr
# creating array
orgnlArray = [Link]('i', [10,5,15,4,6,20,9])
print("Original array:", orgnlArray)
# converting to list
sortedList = [Link]()
# sorting the list
[Link]()
sorted(iterable, reverse=False)
The function returns a new list containing all items from the iterable in ascending order.
Set reverse parameter to True to get a descending order of items.
The sorted() function can be used along with any iterable. Python array is an iterable as
it is an indexed collection. Hence, an array can be used as a parameter to sorted()
function.
22
Example
In this example, we will see the use of sorted() method in sorting an array.
Open Compiler
import array as arr
a = [Link]('i', [4, 5, 6, 9, 10, 15, 20])
sorted(a)
print(a)
JOIN ARRAYS
The process of joining two arrays is termed as Merging or concatenating. Python provides
multiple ways to merge two arrays such as append() and extend() methods. But, before
merging two arrays always ensure that both arrays are of the same data type otherwise
program will throw error.
23
Join two Arrays in Python
To join arrays in Python, use the following approaches −
Open Compiler
import array as arr
Using + operator
We can also use + operator to concatenate or merge two arrays. In this approach, we
first convert arrays to list objects, then concatenate the lists using the + operator and
convert back to get merged array.
Open Compiler
import array as arr
24
a = [Link]('i', [10,5,15,4,6,20,9])
b = [Link]('i', [2,7,8,11,3,10])
x = [Link]()
y = [Link]()
z = x+y
a = [Link]('i', z)
print (a)
Open Compiler
import array as arr
a = [Link]('i', [88, 99, 77, 66, 44, 22])
b = [Link]('i', [12, 17, 18, 11, 13, 10])
[Link](b)
print (a)
array('i', [88, 99, 77, 66, 44, 22, 12, 17, 18, 11, 13, 10])
ARRAY METHOD
The array module in Python offers an efficient object type for representing arrays of basic
values like characters, integers, and floating point numbers. Arrays are similar to lists but
it stores a collection of homogeneous data elements in order. At the time of creating
array's type is specified using a single character type code.
25
Python Array Class
The array class defines several methods, including adding and removing elements,
obtaining information about the array, manipulating array elements, and converting
arrays to and from other data types. Below are categorized methods based on their
functionality. Let's explore and understand the functionality of each method.
[Link]
Methods with Description
.
append(x)
1
Appends a new item with value x to the end of the array.
extend(iterable)
2
Appends items from iterable to the end of the array.
insert(i, x)
3
Inserts a new item with value x before position i.
pop([i])
4 Removes and returns the item with index i. If i is not specified, removes and returns
the last item.
remove(x)
5
Removes the first occurrence of x from the array.
Sr.N
Methods with Description
o.
buffer_info()
1 Returns a tuple (address, length) giving the current memory address and the length in
elements of the buffer used to hold the arrays contents.
count(x)
2
Returns the number of occurrences of x in the array.
26
index(x[, start[, stop]])
Returns the smallest index where x is found in the array. Optional start and stop
3
arguments can specify a sub-range to search.
Sr.N
Methods with Description
o.
reverse()
1
Reverses the order of the items in the array.
byteswap()
2 "Byteswaps" all items of the array, useful for reading data from a file written
on a machine with a different byte order.
Conversion Methods
These methods are used to convert arrays to and from bytes, files, lists, and Unicode
strings.
[Link]
Methods with Description
.
frombytes(buffer)
1 Appends items from the bytes-like object, interpreting its content as an array
of machine values.
tobytes()
2
Converts the array to a bytes representation.
fromfile(f, n)
3
Reads n items from the file object f and appends them to the array.
tofile(f)
4
Writes all items to the file object f.
fromlist(list)
5
Appends items from the list to the array.
tolist()
6
Converts the array to a list with the same items.
7 fromunicode(s)
27
Extends the array with data from the given Unicode string. The array must
have type code 'u'.
tounicode()
8
Converts the array to a Unicode string. The array must have type code 'u'.
EXERCISES.
Example 1
Python program to find the largest number in an array −
Example 2
Python program to store all even numbers from an array in another array −
Open Compiler
import array as arr
a = [Link]('i', [10,5,15,4,6,20,9])
print (a)
28
b = [Link]('i')
for i in range(len(a)):
if a[i]%2 == 0:
[Link](a[i])
print ("Even numbers:", b)
Example 3
Python program to find the average of all numbers in a Python array −
Open Compiler
import array as arr
a = [Link]('i', [10,5,15,4,6,20,9])
print (a)
s=0
for i in range(len(a)):
s+=a[i]
avg = s/len(a)
print ("Average:", avg)
Exercise Programs
Python program find difference between each number in the array and the average
of all numbers
Python program to convert a string in an array
Python program to split an array in two and store even numbers in one array and
odd numbers in the other.
Python program to perform insertion sort on an array.
Python program to store the Unicode value of each character in the given array.
29
30