Open In App
Related Articles

Python Arrays

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

For simplicity, we can think of an array a fleet of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply knowing the count of the steps they are on. The array can be handled in Python by a module named array. They can be useful when we have to manipulate only specific data type values. A user can treat lists as arrays. However, the user cannot constrain the type of elements stored in a list. If you create arrays using the array module, all elements of the array must be of the same type. 

What is an Array in Python?

An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array).
 

Creating an Array

Array in Python can be created by importing an array module. array(data_type, value_list) is used to create an array with data type and value list specified in its arguments. 

This code creates two arrays: one of integers and one of doubles. It then prints the contents of each array to the console.

Python3

import array as arr
a = arr.array('i', [1, 2, 3])
print("The new created array is : ", end=" ")
for i in range(0, 3):
    print(a[i], end=" ")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print("\nThe 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)

Some of the data types are mentioned below which will help in creating an array of different data types. 

Adding Elements to a Array

Elements can be added to the Array by using built-in insert() function. Insert is used 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. append() is also used to add the value mentioned in its arguments at the end of the array. 

The code first imports the `array` module as `arr`. Then, it creates an array of integers named `a` with elements `[1, 2, 3]`. The array is printed before and after inserting the integer `4` at index 1. Similarly, an array of doubles named `b` with elements `[2.5, 3.2, 3.3]` is created and printed before and after appending the double `4.4` to the array.

Python3

import array as arr
a = arr.array('i', [1, 2, 3])
print("Array before insertion : ", end=" ")
for i in range(0, 3):
    print(a[i], end=" ")
print()
a.insert(1, 4)
print("Array after insertion : ", end=" ")
for i in (a):
    print(i, end=" ")
print()
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()
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 




Complexities for Adding elements to the Arrays

Time Complexity: O(1)/O(n) ( O(1) – for inserting elements at the end of the array, O(n) – for inserting elements at the beginning of the array and to the full array
Auxiliary Space: O(1)

Accessing Elements from the Array

In order to access the array items refer to the index number. Use the index operator [ ] to access an item in a array. The index must be an integer. 

This code demonstrates the use of indexing to access elements in arrays. The a[0] expression accesses the first element of the array a, which is 1. The a[3] expression accesses the fourth element of the array a, which is 4. Similarly, the b[1] expression accesses the second element of the array b, which is 3.2, and the b[2] expression accesses the third element of the array b, which is 3.3.

Python3

import array as arr
a = arr.array('i', [1, 2, 3, 4, 5, 6])
print("Access element is: ", a[0])
print("Access element is: ", a[3])
b = arr.array('d', [2.5, 3.2, 3.3])
print("Access element is: ", b[1])
print("Access element is: ", b[2])

                    

Output : 

Access element is:  1
Access element is:  4
Access element is:  3.2
Access element is:  3.3

Complexities for accessing elements in the Arrays

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

Removing Elements from the Array

Elements can be removed from the array by using built-in remove() function but an Error arises if element doesn’t exist in the set. Remove() method only removes one element at a time, to remove range of elements, iterator is used. pop() function can also be used to remove and return an element from the array, but by default it removes only the last element of the array, to remove element from a specific position of the array, index of the element is passed as an argument to the pop() method.
Note – Remove method in List will only remove the first occurrence of the searched element. 

This code demonstrates how to create, print, remove elements from, and access elements of an array in Python. It imports the array module, which is used to work with arrays. It creates an array of integers and prints the original array. It then removes an element from the array and prints the modified array. Finally, it removes all occurrences of a specific element from the array and prints the updated array

Python3

import array
arr = array.array('i', [1, 2, 3, 1, 5])
print("The new created array is : ", end="")
for i in range(0, 5):
    print(arr[i], end=" ")
 
print("\r")
print("The popped element is : ", end="")
print(arr.pop(2))
print("The array after popping is : ", end="")
for i in range(0, 4):
    print(arr[i], end=" ")
 
print("\r")
arr.remove(1)
print("The array after removing is : ", end="")
for i in range(0, 3):
    print(arr[i], end=" ")

                    

Output
The new created array is : 1 2 3 1 5 
The popped element is : 3
The array after popping is : 1 2 1 5 
The array after removing is : 2 1 5 



Complexities for Removing elements in the Arrays

Time Complexity: O(1)/O(n) ( O(1) – for removing elements at the end of the array, O(n) – for removing elements at the beginning of the array and to the full array
Auxiliary Space: O(1)

Slicing of an Array

In Python array, there are multiple ways to print the whole array with all the elements, but to print a specific range of elements from the array, we use Slice operation. Slice operation is performed on array with the use of colon(:). To print elements from beginning to a range use [:Index], to print elements from end use [:-Index], to print elements from specific Index till the end use [Index:], to print elements within a range, use [Start Index:End Index] and to print whole List with the use of slicing operation, use [:]. Further, to print whole array in reverse order, use [::-1]. 

This code employs slicing to extract elements or subarrays from an array. It starts with an initial array of integers and creates an array from the list. The code slices the array to extract elements from index 3 to 8, from index 5 to the end, and the entire array. The sliced arrays are then printed to demonstrate the slicing operations.

Python3

import array as arr
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
a = arr.array('i', l)
print("Initial Array: ")
for i in (a):
    print(i, end=" ")
Sliced_array = a[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_array)
Sliced_array = a[5:]
print("\nElements sliced from 5th "
      "element till the end: ")
print(Sliced_array)
Sliced_array = a[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_array)

                    

Output
Initial Array: 
1 2 3 4 5 6 7 8 9 10 
Slicing elements in a range 3-8: 
array('i', [4, 5, 6, 7, 8])

Elements sliced from 5th element till the end: 
array('i', [6, 7, 8, 9, 10])

Printing all elements...



Searching Element in an Array

In order to search an element in the array we use a python in-built index() method. This function returns the index of the first occurrence of value mentioned in arguments. 

Example: The code demonstrates how to create an array in Python, print its elements, and find the indices of specific elements. It imports the array module, creates an array of integers, prints the array using a for loop, and then uses the index() method to find the indices of the first occurrences of the integers 2 and 1.

Python3

import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
print("The new created array is : ", end="")
for i in range(0, 6):
    print(arr[i], end=" ")
 
print("\r")
print("The index of 1st occurrence of 2 is : ", end="")
print(arr.index(2))
print("The index of 1st occurrence of 1 is : ", end="")
print(arr.index(1))

                    

Output
The new created array is : 1 2 3 1 2 5 
The index of 1st occurrence of 2 is : 1
The index of 1st occurrence of 1 is : 0




Complexities for searching elements in the Arrays

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

Updating Elements in a Array

In order to update an element in the array we simply reassign a new value to the desired index we want to update. 

Example: This code illustrates the functionality of modifying elements within an array using indexing. It imports the array module, creates an array of integers, and prints the initial array. Then, it modifies two elements of the array at specific indexes and prints the updated array. This serves to demonstrate how indexing allows for dynamic manipulation of array contents.

Python3

import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
print("Array before updation : ", end="")
for i in range(0, 6):
    print(arr[i], end=" ")
 
print("\r")
arr[2] = 6
print("Array after updation : ", end="")
for i in range(0, 6):
    print(arr[i], end=" ")
print()
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 



Complexities for updating elements in the Arrays

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

Different Operations on Python Arrays

Counting Elements in a Array

In order to count elements in an array we need to use count method.

Example: The code demonstrates how to determine the frequency of a particular element within an array. It imports the array module, creates an array of integers, counts the occurrences of the number 2 using the count() method, and finally prints the result. This code snippet effectively showcases the ability to analyze the distribution of elements in arrays.

Python3

import array
my_array = array.array('i', [1, 2, 3, 4, 2, 5, 2])
count = my_array.count(2)
print("Number of occurrences of 2:", count)

                    

Output
Number of occurrences of 2: 3




Complexities for counting elements in the Arrays

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

Reversing Elements in a Array

In order to reverse elements of an array we need to simply use reverse method.

Example: The presented code demonstrates the functionality of reversing the order of elements within an array using the reverse() method. It imports the array module, creates an array of integers, prints the original array, reverses the order of elements using reverse(), and then prints the reversed array. This effectively illustrates the ability to modify the arrangement of elements in an array.

Python3

import array
my_array = array.array('i', [1, 2, 3, 4, 5])
print("Original array:", *my_array)
my_array.reverse()
print("Reversed array:", *my_array)

                    

Output
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1




Complexities for reversing elements in the Arrays:

Time Complexity: O(n)
Auxiiary Space: O(1)

Extend Element from Array

In the article,we will cover the python list extend() and try to understand the Python list extend().

What is extend element from array?

In Python, an array is used to store multiple values or elements of the same datatype in a single variable. The extend() function is simply used to attach an item from iterable to the end of the array. In simpler terms, this method is used to add an array of values to the end of a given or existing array.

Syntax of list extend()

The syntax of the extend() method:

list.extend(iterable)

Here,all the element of iterable are added to the end of list1

Example 1:

The provided code demonstrates the capability of extending an array to include additional elements. It imports the array module using an alias, creates an array of integers, prints the array before extension, extends the array using the extend() method, and finally prints the extended array. This concisely illustrates the ability to add elements to an existing array structure

Python3

import array as arr
a = arr.array('i', [1, 2, 3,4,5])
print("The before array extend  : ", end =" ")
for i in range (0, 5):
   
    print (a[i], end =" ")
     
print()
a.extend([6,7,8,9,10])
print("\nThe array after extend :",end=" ")
 
for i in range(0,10): 
   
    print(a[i],end=" ")
     
print()

                    

Output
The before array extend  :  1 2 3 4 5 

The array after extend : 1 2 3 4 5 6 7 8 9 10 




Example 2:

The provided code demonstrates the capacity to extend arrays with various data types, including integers and floats. It utilizes the array module, creates arrays of both data types, and extends them using the extend() method. The arrays are then printed before and after extension to illustrate the changes. This effectively showcases the ability to append elements to arrays of different data representations.

Python3

import array as arr
a=arr.array('i',[1,2,3,4,5,6])
print("The Before extend array is :",end=" ")
for i in range(0,6):
   
    print(a[i],end=" ")
     
print()
a.extend([7,8,9,10,11,12])
print("\nThe After extend array is :",end=" ")
 
for i in range(0,12):
   
    print(a[i],end=" ")
 
print()
b = arr.array('d', [2.1,2.2,2.3,2.4,2.5,2.6])
 
print("\nThe before extend array is :",end=" ")
 
for i in range(0,6):
   
  print(b[i],end=" ")
   
print()
b.extend([2.6,2.7,2.8,2.9])
 
print("\nThe after extend array is :",end=" ")
 
for i in range(0,9+1):
   
  print(b[i],end=" ")
   
print()

                    

Output
The Before extend array is : 1 2 3 4 5 6 

The After extend array is : 1 2 3 4 5 6 7 8 9 10 11 12 

The before extend array is : 2.1 2.2 2.3 2.4 2.5 2.6 

The after extend array is : 2.1 2.2 2.3 2.4 2...



Complexities for extend element from array:

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

More Information Resource Related to Python Array:



Last Updated : 21 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads