What is an Array in Python?
An array is a data structure that can contain or hold a fixed number of elements that are of the same Python data type. An array is composed of an element and an index. Index in an array is the location where an element resides. All elements have their respective indices. Index of an array always starts with 0.
Unlike other programming languages, such as Java, C, C++, and more, arrays are not that popular in Python since there are many iterable data types in Python that are flexible and fast to use such as Python lists. However, arrays in Python are still used in certain cases. In this module, we will learn all about all the important aspects of arrays in Python, from what they are to when they are used.
So, without further delay, let’s get started.
Array Vs List in Python
The basic difference between arrays and lists in Python is that lists are flexible and can hold completely arbitrary data of any data type while arrays can only hold data of the same data type.
Arrays are considered useful in terms of memory efficiency, but they are usually slower than lists. As mentioned above, the Python array module is not that popular to use, but they do get used in certain cases such as:
Creating an Array in Python
The array module supports numeric arrays in Python. So, to create an array in Python, we will have to import the array module. Following is the syntax for creating an array. Now to understand how to declare an array in Python, let us take a look at the python array example given below:
from array import *
arraname = array(typecode, [Initializers])
Here, typecode is what we use to define the type of value that is going to be stored in the array. Some of the common typecodes used in the creation of arrays in Python are described in the following table.
Type Code |
C Type |
Python Data Type |
Minimum Size in Bytes |
‘b’ |
signed char |
int |
1 |
‘B’ |
unsigned char |
int |
1 |
‘u’ |
Py_UNICODE |
Unicode character |
2 |
‘h’ |
signed short |
int |
2 |
‘H’ |
unsigned short |
int |
2 |
‘i’ |
signed int |
int |
2 |
‘I’ |
unsigned int |
int |
2 |
‘l’ |
signed long |
int |
4 |
‘L’ |
unsigned long |
int |
4 |
‘f’ |
float |
float |
4 |
‘d’ |
double |
float |
8 |
Now, let’s create a Python array using the above-mentioned syntax.
Example:
import array as arr
a = arr.array(‘I’, [2,4,6,8])
print(a)
Output:
array(‘I’, [2, 4, 6, 8])
Accessing a Python Array Element
We can access the elements of an array in Python using the respective indices of those elements, as shown in the following example.
from array import*
array_1 = array(‘i’, [1,2,3,4,5])
print (array_1[0])
print (array_1[3])
1
4
The index of the array elements starts from 0. When we printed the value of array1[0], it displayed the first element.
Get 100% Hike!
Master Most in Demand Skills Now!
Basic Operations of Arrays in Python
Following are some of the basic operations supported by the array module in Python:
- Traverse of an Array in Python: Iterating between elements in an array is known as traversing. We can easily iterate through the elements of an array using Python for loop as shown in the example below.
Example:
from array import *
array_1 = array(‘i’, [1,2,3,4,5])
for x in array_1:
print (x)
Output:
1
2
3
4
5
- Insertion of Elements in an Array in Python: Using this operation, we can add one or more elements to any given index.
Example:
from array import *
array_1 = array(‘i’, [1,2,3,4,5])
array_1.insert(1,6)
for x in array_1:
print (x)
Output:
1
6
2
3
4
5
- Deletion of Elements in an Array in Python: Using this operation, we can delete any element residing at a specified index. We can remove any element using the built-in remove() method.
Example:
from array import *
array_1 = array(‘i’, [1,2,3,4,5])
array_1.remove(2)
For x in array_1:
print (x)
Output:
1
3
4
5
- Searching Elements in an Array in Python: Using this operation, we can search for an element by its index or its value.
Example:
from array import *
array_1 = array(‘i’, [1,2,3,4,5])
print (array_1.index(3))
Output:
2
In the above example, we have searched for the element using the built-in index() method. Using index(3) returned the output 2 which means that 3 is at the index number 2 in array_1. If the searched value is not present in the array, then the program will return an error.
- Updating Elements in an Array in Python: Using this operation, we can update an element at a given index.
Example:
from array import *
array_1 = array(‘i’, [1,2,3,4,5])
array_1[2] = 100
for x in array_1:
print(x)
Output:
1
2
100
4
5
In the above example, we have updated the already existing value at index 2 instead of adding a new element.
2D Arrays in Python
A 2D Array is basically an array of arrays. In a 2D array, the position of an element is referred to by two indices instead of just one. So it can be thought of as a table with rows and columns of data.
Student_marks = [[96, 91, 70, 78, 97], [80, 87, 65, 89, 85], [90, 93, 91, 90, 94], [57, 89, 82, 69, 60], [72, 85, 87, 90, 69]]
print(Student_marks[1])
print(Student_marks[0])
print(Student_marks[2])
print(Student_marks[3][4])
The output will be
[80, 87, 65, 89, 85]
[96, 91, 70, 78, 97]
[90, 93, 91, 90, 94]
60
Dynamic Array in Python
A dynamic array is similar to an array, but the difference is that its size can be dynamically modified at runtime. The programmer doesn’t need to specify how large an array will be, beforehand.
The elements of a normal array occupy a contiguous block of memory, and once created, the size can’t be changed. A dynamic array can, once the array is filled, allocate a bigger chunk of memory, copy the contents from the original array to this new space, and continue to fill the available slots.
We use a built-in library called ctypes, to implement Dynamic Arrays in Python.
import ctypes
class DynamicArray(object):
def __init__(self):
self.n = 0
self.capacity = 1
self.A = self.make_array(self.capacity)
def __len__(self):
return self.n
def __getitem__(self, k):
if not 0 <= k <self.n:
return IndexError('K is out of bounds !')
return self.A[k]
def append(self, ele):
if self.n == self.capacity:
self._resize(2 * self.capacity)
self.A[self.n] = ele
self.n += 1
def insertAt(self,item,index):
if index<0 or index>self.n:
print("please enter appropriate index..")
return
if self.n==self.capacity:
self._resize(2*self.capacity)
for i in range(self.n-1,index-1,-1):
self.A[i+1]=self.A[i]
self.A[index]=item
self.n+=1
def delete(self):
if self.n==0:
print("Array is empty deletion not Possible")
return
self.A[self.n-1]=0
self.n-=1
def removeAt(self,index):
if self.n==0:
print("Array is empty deletion not Possible")
return
if index<0 or index>=self.n:
return IndexError("Index out of bound")
if index==self.n-1:
self.A[index]=0
self.n-=1
return
for i in range(index,self.n-1):
self.A[i]=self.A[i+1]
self.A[self.n-1]=0
self.n-=1
def _resize(self, new_cap):
B = self.make_array(new_cap)
for k in range(self.n):
B[k] = self.A[k]
self.A = B
self.capacity = new_cap
def make_array(self, new_cap):
return (new_cap * ctypes.py_object)()
Take your Python programming skills to the next level with Python NumPy!
Array Input in Python
string1 = input('Enter the elements separated by space ')
print("\n")
arr1 = string1.split()
print('Array = ', arr1)
The output will be
Enter the elements separated by space
7 8 9 10
Array = ['7', '8', '9', '10']
Array Index in Python
The index of a value in an array is that value’s location within the array. The counting of array indices in Python starts at 0 and ends at n-1, where n is the total number of elements in the array.
arr1 = [2,5,7,8]
Element |
Index |
2 |
0 |
5 |
1 |
7 |
2 |
8 |
3 |
Array Programs in Python
Let’s go through some common Array programs in Python.
Array Length in Python
Use the len() method to return the length of an array (the number of elements in an array).
cars = ["Ford", "Volvo", "BMW"]
x = len(cars)
print(x)
The output will be 3
Sum of Array in Python
string1 = input('Enter the elements separated by space ')
print("\n")
arr1 = string1.split()
print('Array = ', arr1)
for i in range(len(arr1)):
arr1[i] = int(arr1[i])
print("Sum = ", sum(arr1))
Enter the elements separated by space 5 6 7 8
Array ['5', '6', '7', '8']
Sum = 26
Sort Arrays in Python
Python provides a built-in function to sort arrays. The sort function can be used to sort the list in both ascending and descending order.
numbers = [1, 3, 4, 2]
numbers.sort()
print(numbers)
The output will be [1, 2, 3, 4]
Reverse Array in Python
arr = [1, 2, 3, 4, 5];
print("The array is:", arr)
arr2 = arr[: : -1]
print("The Array in reversed order:", arr2);
The output will be
The array is: [1, 2, 3, 4, 5]
The Array in reversed order: [5, 4, 3, 2, 1]
Array Slice in Python
To pull out a section or slice of an array, the colon operator: is used when calling the index.
import numpy as np
a = np.array([2, 4, 6])
b = a[0:2]
print(b)
The output will be [2 4]
List to Array in Python
numpy.array() can be used to convert a list into an array.
import numpy as np
list1 = [2,4,6,8,10]
arr1 = np.array(list1)
print (arr1)
print (type(arr1))
The output will be
[ 2 4 6 8 10]
<class 'numpy.ndarray'>
String to Array in Python
def Convert(string):
a = list(string.split(" "))
return a
str1 = "Intellipaat Python Tutorial"
print(Convert(str1))
The output will be
['Intellipaat', 'Python', 'Tutorial']
Python Array vs List
List |
Array |
Lists are built-in and don’t have to be imported. |
We need to import Array before using them. |
Lists can store different types of values |
Arrays only have the same type of values |
Lists are less compatible. |
Arrays are comparatively more compatible. |
Direct Arithmetic Operations can’t be done on Lists |
Direct Arithmetic Operations can be done on Arrays |
The entire list can be printed using explicit looping |
The entire array can be printed without using explicit looping |
Lists are better for storing longer sequences of data items. |
Arrays are better for storing shorter sequences of data items. |
Lists consume more memory. |
Arrays consume less memory. |
With this, we have come to the end of this module in Python Tutorial. We learned about arrays in Python 3, how to define an array in Python 3, accessing a Python Array, and the different operations of Python arrays. Now, if you are interested in knowing why python is the most preferred language for data science, you can go through this Python data science tutorial.
Further, check out our offers for Python training Courses and also refer to the trending Python developer interview questions prepared by the industry experts.