Table of contents
1.
Introduction 
2.
What are Arrays in Python?
3.
Creating an Array in Python
3.1.
Implementation in Python
3.1.1.
Output
3.2.
Time Complexity
4.
Adding Elements to a Array
4.1.
Implementation in Python
4.1.1.
Output
4.2.
Time Complexity
5.
Removing Elements from the Array
5.1.
Implementation in Python
5.1.1.
Output
5.2.
Time Complexity
5.3.
Slicing of a Array
5.4.
Implementation in Python
5.4.1.
Output
5.5.
Time Complexity
6.
Searching element in a Array
6.1.
Implementation in Python
6.1.1.
Output
7.
Time complexity
8.
Updating Elements in a Array
8.1.
Implementation in Python
8.1.1.
Output
8.2.
Time complexity
9.
Counting Elements in a Array
9.1.
Implementation in Python
9.1.1.
Output
9.2.
Time Complexity
10.
Reversing Elements in a Array
10.1.
Implementation in Python
10.2.
Time complexity
11.
Types of Arrays in Python
12.
How to change or add elements?
13.
Advantages of using Arrays in Python
14.
Disadvantages of using Arrays in Python
15.
Frequently Asked Questions
15.1.
How to declare arrays in Python?
15.2.
When to use array Python?
15.3.
What are the 4 types of array in Python?
16.
Conclusion
Last Updated: Jul 9, 2024
Easy

Arrays in Python

Author Yukti Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

Before we start, let's consider a simple example that will allow you to learn Arrays in Python quickly and efficiently. Imagine you need to maintain track of Bitcoin market prices during a pandemic.

array in python

Instead of using separate variables for each day, we can use an Array to store all the prices. This article will explain how this approach works in such circumstances. Let's start learning about Arrays in Python now.

Also see, Merge Sort Python

What are Arrays in Python?

An array is a collection of variables of the same type referred to by the same name. Arrays are made up of contiguous memory regions. The lowest address corresponds to the first element, while the highest address corresponds to the last element. Arrays allow you to aggregate objects of the same type into a bigger unit.

Let’s have a look at how arrays help in keeping the count of bitcoin market prices.

bitcoinCount = [ 567$, 570$, 600$, 550$ ]

Arrays in Python

The above Representation of the Array elements depicts some facts about arrays in python, which are significant for mastering them.

  • Indexing on Arrays begins from 0. To retrieve the elements, the index plays a vital role. For example, if I want to access the first element in my array, I can simply write array_name[index],.i.e, bitcoinCount[0].

 

Similarly, we can access the other elements in an array.

  • The location where the elements are stored is known as memory addresses. The addresses are in Hexadecimal form. Memory refers to the RAM (Random access memory), where all these elements are stored. 
     
  • When performing any operation on Arrays, the control points to the base address (or starting address). We can also access the array elements using the base address. 

 

Assume any index from the above example:

Address ( nth) = Base address + ( n x Size of the data type)

 

where â€˜n’ is the desired element’s index, Base Address is the 0x00500, Size = ( Since the array is of integer type, the size is 4)

Let’s access the 3rd element:

n=3;
Address( 3rd)  = 0x00500 + ( 3 x ( 4))
                      = 0x00500 + 12
                      = 0x0050A  

 

Now, we can easily access the element present at that address. The Time Complexity will be 0(1) as it takes a constant time.

  • In python, an Array can be handled by a module named Array. In the array module, we can only manipulate the same type of data. But we’ve discussed that the array is of the same kind. Generally, arrays are of two types:
     
  • Static Arrays: Static arrays are of the same type, thus, the same size. Moreover, we cannot modify its size. In this article, we will be going through the static arrays.
     
  • Dynamic Arrays: Dynamic arrays are precisely the opposite of static arrays. It may have different data types, and we can manipulate its size. For example:  In java, ArrayList is the dynamic array, and In C++, std::vector. 

Creating an Array in Python

You must import the array module to create and build an array in Python. After importing the array module, you can operate the array function to build arrays in Python.

Implementation in Python

# Imported the library
import array

my_array = array.array('i', [1, 2, 3, 4, 5])

print("The new created array is : ", end=" ")
for i in range(0, 5):
    print(my_array[i], end=" ")

Output

Output

Time Complexity

The time complexity of the above code is O(1). It will always take the same amount of time to execute regardless of the size of the array.

Adding Elements to a Array

To add a single element, use the append() method; to add an array, use the extend() method to merge it at the end of the existing array. 

Implementation in Python

import array as arr

my_array = arr.array('i', [1, 2, 3, 4])

# Use append function to add element
my_array.append(7)
print('Use append() function:', my_array)

# Use extend function to add the list of element
my_array.extend([8, 9, 10])
print('Use extend() function:', my_array)

Output

output

Time Complexity

Time complexity of the function append is O(1) and for the extend function is O(k) where ‘k’ is the number of elements in the list being extended.

Removing Elements from the Array

In Python, elements can be removed from an array using remove() (for specific elements) and pop() (for the last index). 

Note: if we give a non-existing element, it will display an error.

Implementation in Python

import array as arr

my_array = arr.array('i', [2, 3, 6, 7])

# used remove function
my_array.remove(2)

print('Updated Array after removing: ', my_array)

my_array1 = arr.array('i', [2, 3, 6, 7])

# used pop function
my_array1.pop()

print('Updated Array after poping: ', my_array1

Output

Output

Time Complexity

Time complexity of the function remove is O(n) or O(k) and for the pop function is O(1).

Slicing of a Array

In Python, slicing allows in extracting a specific range of elements from an array, list, or string using the syntax start:stop. 

Implementation in Python

l = [4, 6, 1, 8, 9]

# Extract elements
sliced_list = l[1:4]

print(sliced_list)  

Output

Output

Time Complexity

The time complexity of the code is O(n), but we consider it as O(1) for specific purposes.

Searching element in a Array

Python allows searching for elements in an array using the index() method. It returns the index of the first occurrence of the selected element. If the component is absent in the array, it gives a ValueError.

Implementation in Python

import array as arr

my_array = arr.array('i', [2, 5, 8, 9])

index = my_array.index(8)

print('Index of the element is: ', index)

Output

Output

Time complexity

The time complexity of searching an element is O(n), where n is the number of elements in the array. 

Updating Elements in a Array

To modify a value in an array, select the position you want and replace the old value with the new one. 

Note: Not to choose a position outside the array's boundaries, or you'll get an error saying, "Index out of range".

Implementation in Python

import array as arr

my_array = arr.array('i', [10, 16, 23, 45])

print('Before update: ', my_array)

my_array[3] = 150

print('After update: ',my_array)

Output

Output

Time complexity

The time complexity of the code is O(n). When you update an element in an array using the index (my_array[3] = 150 in this case), it accesses and changes the value at that specific index.

Counting Elements in a Array

To count the number of elements in a Python array, use the built-in len() function, which returns the size of the array.

Implementation in Python

array = [4, 8, 13, 18, 20]

count_element = len(array)

print(count_element)

Output

Output

Time Complexity

The code's time complexity is O(1). Python's len() function directly returns the array's size, known by the system, without iterating or traversing the elements.

Reversing Elements in a Array

In Python, you can quickly reverse an array using the built-in .reverse() function, which flips the array elements by creating a reverse iterator.

Implementation in Python

import array as arr

my_array = arr.array('i', [4, 8, 12, 67, 90])

print('Before reversing: ', my_array)

# Use reverse function
my_array.reverse()

print('After reversing: ', my_array)


Output

Output

Time complexity

The time complexity of the code is O(n), where n is the number of elements in the array. The 'my_array.reverse()' function reverses the array in place by swapping the elements.

Types of Arrays in Python

So far, we have discussed the single-dimensional array, which is the one type of array in python. The second type is a Multidimensional array.

Multidimensional arrays in python are the arrays present within arrays. As the name suggests, multi means more than one dimension. A multidimensional array, to be exact, assigns several indices to each element in the array. Multiplying the sizes of all the dimensions yields the total number of elements contained in the array.

Multidimensional arrays can further be divided into various types:-

  • Two-Dimensional array
  • Three-Dimensional array
  • Four-Dimensional array 
  • Five-Dimensional array and the list goes on.

 

A two-dimensional array has two subscripts [ ] [ ], the first of which indicates the number of rows, and the second represents the number of columns. A two-dimensional array is commonly referred to as a matrix.

For example:

int num [34] [50] → Declaration of the 2-D array of type int. 
Number of Elements = 34×50 = 1700 elements can be stored in the num array.

 

Note:- Array module doesn’t support multidimensional arrays. We need to import another module named NumPy

NumPy, which stands for Numerical Python, is a library consisting of multidimensional array objects and a collection of routines for processing those arrays. Using NumPy, mathematical and logical operations on arrays can be performed. 

Let’s verify the above statement:

# array module
from array import *

# 2-D array initialized
arr = array('u', ['c', 'o', 'd', 'e'], ['m', 'o', 'd', 'e'])

print(arr)


OUTPUT

Traceback (most recent call last):
  File "C:\Users\HP\PycharmProjects\pythonProject\main.py", line 2, in <module>
    arr = array('u', ['c', 'o', 'd', 'e'], ['m', 'o', 'd', 'e'])   # 2-D array initialized
TypeError: array() takes at most 2 arguments (3 given)


The output shows an error. Error is array( ) only accepts two parameters (and we have given it three). Importing the NumPy module is required to use the multidimensional array. The scientific python environment is built upon NumPy. This library provides a particular data structure for high-performance numerical calculation.

Also see, Fibonacci Series in Python

How to change or add elements?

To change or add elements in programming, follow these steps:

  • Access the Data Structure: Identify the data structure where you want to make changes, such as an array or dictionary.
     
  • Specify the Modification: Determine whether you want to change existing elements or add new ones.
     
  • Use Appropriate Methods: For changing elements, access the specific element and assign it a new value. For adding elements, use methods like append() for arrays or put() for dictionaries.
     
  • Handle Errors: Ensure error handling for cases like out-of-bounds indexing or existing key clashes when adding elements.
     
  • Test: Verify changes to ensure they meet desired outcomes.

Advantages of using Arrays in Python

  • Cache Friendly – In an array, values are near each other in memory. To be more specific, they are in contiguous form; hence, the elements can easily be accessed from CPU to cache. This brings us to the conclusion that iteration over an array is faster than any other iteration.
     
  • Advantages over variables – A static array is classified as the Homogeneous collection of data. For any purpose, if the user wishes to store multiple values of the same type, arrays are the best option.
     
  • Helps in reusability of code – The significant advantage of an array is that it can be declared once and reused multiple times at any section in the program. Thus, it helps in the reusability of the code.
     
  • Multi-dimensional arrays – Multidimensional arrays are beneficial while handling the arrays within arrays. When the user wants to store the data in a tabular format, multi-dimensional arrays come into play. 

Disadvantages of using Arrays in Python

  • Fixed Size: Arrays have a fixed size, making it challenging to dynamically resize them without overhead. 
     
  • Homogeneous Elements: Arrays in Python can only contain elements of the same data type, limiting flexibility compared to other data structures. 
     
  • Limited Functionality: Arrays offer basic functionality for element access and modification but lack advanced operations available in other data structures like lists or dictionaries. 
     
  • Memory Overhead: Arrays require contiguous memory allocation, leading to potential memory wastage and fragmentation. 
     
  • No Built-in Methods: Arrays lack built-in methods for operations like sorting or searching, requiring manual implementation.

Frequently Asked Questions

How to declare arrays in Python?

In Python, you can declare arrays by simply defining a variable and assigning it a list of values enclosed in square brackets. For example: my_array = [1, 2, 3, 4, 5]

This creates an array named my_array containing the specified values. Python allows arrays to hold elements of different data types within the same array.

When to use array Python?

Use arrays in Python when you need a data structure to keep a fixed-size collection of elements of the same data type for efficient memory utilization and more secured access.

What are the 4 types of array in Python?

The 4 types of array are one dimensional array, two dimensional array, three dimensional array and four dimensional array.

Conclusion

To summarise the subject, we looked at arrays in Python using an array module. The array module’s disadvantage is that it does not handle multidimensional arrays in Python. The solution will be discussed in our upcoming blogs, which will make use of the NumPy module. Till then, keep practicing the programming questions on Code studio

Check out the following problems - 

You can also refer to these articles for more details on python programming language- Dictionary in pythonPython ArchivesPattern Problems.

Happy Learning Ninja! 

Live masterclass