All Courses
Python Arrays

Python arrays are a collection of elements stored in contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easy to calculate the position of each element by simply adding an offset to the base value. Therefore the location of the first element of the array (usually indicated by the array name). Arrays are popular in most programming languages ​​such as C / C ++ and JavaScript. Combining arrays can save you a lot of time by reducing the overall code size. It is used to store multiple values ​​in a single variable. If each variable has a list of items stored as follows:

bike1 = "Kawasaki"
bike2 = "Ducati"
bike3 = "Duke"

If you want to loop through the bikes and find a particular bike, you can use an array.
arrays can be managed in Python by a module called arrays. This is useful if you only need to edit specific data values. The terms for understanding the concept of arrays are:

  • Elements– Each item stored in an array is called an element.
  • Index– The position of an element in the array has a numeric index used to identify the position of the element.

Arrays Vs List in Python

The basic difference between arrays and lists in Python is that lists are flexible and can completely contain data of any data type, whereas arrays can only contain data of the same data type. Therefore arrays are considered useful from a storage efficiency standpoint but are usually slower than lists.

Arrays Representation

Arrays can be declared in different languages ​​in different ways. Here are some important points to keep in mind:

  • The index starts at 0.
  • The index allows you to access any element.
  • The length of the array defines the capacity to store the elements.

Arrays operations

Some of the basic operations supported by arrays are:

  • Traverse-Outputs each element one at a time.
  • Insert-Adds an item to the specified index.
  • Delete-Deletes the element at the specified index.
  • Search-Searches for an item by the specified index or value.
  • Update-Updates the item at the specified index.

Creating an Arrays

Syntax:

from array import *  
arrayName = array(typecode, [initializers]) 

Arrays in Python can be created by importing an array module. array (data_type, value_list) is used to create an array with the list of data types and values ​​specified by the arguments.

Python Arrays

For Example:

# Python program to demonstrate
# Creation of Array

# importing "array" for array creations
import array as arr

# creating an array with integer type
a = arr.array('i', [1, 2, 3])

# printing original array
print ("The new created array is : ", end =" ")
for i in range (0, 3):
	print (a[i], end =" ")
print()

# creating an array with float type
b = arr.array('d', [2.5, 3.2, 3.3])

# printing original array
print ("The new created array is : ", end =" ")
for i in range (0, 3):
	print (b[i], end =" ")

Output:

The new created array is :  1 2 3 
The new created array is :  2.5 3.2 3.3 

Complexities for Creation of Arrays:

  • Time Complexity: O(1)
  • Auxiliary Space: O(n)

Here we use the type code to define the type of the value stored in the array. The following table describes some of the common type codes used when creating arrays in Python.

Type CodeC TypePython Data TypeMinimum Size in Bytes
‘b’signed charint1
‘B’unsigned charint1
‘u’Py_UNICODEUnicode character2
‘h’signed shortint2
‘H’unsigned shortint2
‘i’signed intint2
‘I’unsigned intint2
‘l’signed longint4
‘L’unsigned longint4
‘f’floatfloat4
‘d’doublefloat8

Accessing a Python Array Element

To access the elements of an array in Python, use the index of each of those elements, as shown in the following example Program.

For Example:

import array as arr  
a = arr.array('i', [2, 4, 6, 8])  
print("First element:", a[0])  
print("Second element:", a[1])  
print("Second last element:", a[-1])  

Output:

First element: 2
Second element: 4
Second last element: 8

Explanation:

In the above example, we imported the array, defined a variable named “a” to hold the elements of the array and output the elements by accessing the elements through the index of the array.

Basic Operations of Arrays in Python

Below are some of the basic operations supported by the Python array module.

1. Traverse of an Array in Python:

Iterations between elements in an array are called traverses. You can easily iterate through the elements of an array using Python for loop, as shown in the following example.

For 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

2. Insertion of Elements in an Array in Python:

You can add elements to the array using the built-in insert() function. Inserts are used to insert one or more data items into an array. Depending on your requirements, you can add new elements to any index in the first, last, or array. append() is also used to add the value given in the argument to the end of the array.

# Python program to demonstrate
# Adding Elements to a Array

# importing "array" for array creations
import array as arr

# array with int type
a = arr.array('i', [1, 2, 3])


print ("Array before insertion : ", end =" ")
for i in range (0, 3):
	print (a[i], end =" ")
print()

# inserting array using
# insert() function
a.insert(1, 4)

print ("Array after insertion : ", end =" ")
for i in (a):
	print (i, end =" ")
print()

# array with float type
b = arr.array('d', [2.5, 3.2, 3.3])

print ("Array before insertion : ", end =" ")
for i in range (0, 3):
	print (b[i], end =" ")
print()

# adding an element using append()
b.append(4.4)

print ("Array after insertion : ", end =" ")
for i in (b):
	print (i, end =" ")
print()

Output : 

Array before insertion : 1 2 3 
Array after insertion :  1 4 2 3 
Array before insertion : 2.5 3.2 3.3 
Array after insertion :  2.5 3.2 3.3 4.4 

3. Deletion of Elements in Arrays in Python:

Elements can be removed from the array by using the built-in remove() function but an Error arises if the element doesn’t exist in the set. If you want to remove any value from the array, you can use the index of a particular element to remove it.

For 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

4. Searching Elements in an Array in Python: 

To find the elements in the array, use Python’s built-in index() method. This function returns the index of the first occurrence of the value specified by the argument.

For 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 used the built-in index () method to find the element. Using index (3) returns output 2. This means that 3 is at index number 2 of array_1. If the value you are looking for is not in the array, the program will return an error.

5. Updating Elements in an Array in Python: 

To update an element in an array, simply assign a new value to the index you want to update.

For Example:

# Python code to demonstrate
# how to update an element in array

# importing array module
import array

# initializing array with array values
# initializes array with signed integers
arr = array.array('i', [1, 2, 3, 1, 2, 5])

# printing original array
print ("Array before updation : ", end ="")
for i in range (0, 6):
	print (arr[i], end =" ")

print ("\r")

# updating a element in a array
arr[2] = 6
print("Array after updation : ", end ="")
for i in range (0, 6):
	print (arr[i], end =" ")
print()

# updating a element in a array
arr[4] = 8
print("Array after updation : ", end ="")
for i in range (0, 6):
	print (arr[i], end =" ")

Output:

Array before updation : 1 2 3 1 2 5 
Array after updation : 1 2 6 1 2 5 
Array after updation : 1 2 6 1 8 5 

Finding the length of an array

The length of an array is defined as the number of elements in the array. Returns an integer value equal to the total number of elements in this array.

Syntax

len(array_name)

For Example:

# Python program to demonstrate working
# of len()
a = []
a.append("Welcome")
a.append("to")
a.append("eMexo")
a.append("Technologies")
print("The length of list is: ", len(a))

Output:

The length of list is:  4

Array Concatenation

We can easily concatenate any two arrays using the + symbol.

For Example:

a=arr.array('d',[1.1 , 2.1 ,3.1,2.6,7.8])  
b=arr.array('d',[3.7,8.6])  
c=arr.array('d')  
c=a+b  
print("Array c = ",c)  

Output:

Array c= array('d', [1.1, 2.1, 3.1, 2.6, 7.8, 3.7, 8.6])

Explanation:

In the above example, we have defined a variable named “a, b, c” that holds the values ​​of the array.