What are Arrays in Python?

What are Arrays in Python?
What are Arrays in Python?

Introduction 

Before getting started, let’s visualise an example that will help you understand Array’s use case in Python. Imagine you have been told to keep the count of the Bitcoin market prices during the pandemic.

What will you do? Will you keep a separate variable count for each day? 

Of Course not. What can be the solution then?

We can use arrays to store all the prices instead of creating different variables for each day. In this article, we will go through how this approach works in such types of cases. Let’s get started with Arrays in python now:

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$ ]

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:

blog banner 1
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 = 4 ( 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

First, to create an array, we need to import the array module, as we’ve discussed above. 

import array as arr   #arr is an alias

The syntax for creating an array:

array module.array( 'typeCode ', [value_list] )  

# typeCode is a single character of any data type

TypeCode = The data type is specified at the array creation time using a single character called the type code. For example:

Let’s create the array of integer types:

import array as arr
vals = arr.array('i', [5,6,7,8])    # i is the typeCode for int
print(vals)                               # print array stored in variable vals

OUTPUT

array('i', [5, 6, 7, 8])

Below are the type codes for the data types which we can use for the creation of arrays.

Source: ridicurious

Let’s see the Implementation to illustration:

# Program to create a array
# import array module
import array as arr     

# d is the typeCode for float                                      
vals_float = arr.array('d', [3.4, 6.5, 7.6, 8.9])   

# u is the typeCode for char
vals_char = arr.array('u', ['a', 'i', 'o', 'u', 'e'])         

# printing float array using for loop
print("First array : ", end="  ")

for i in range(0, 4):                      
   print(vals_float[i], end="   ")
print()

# printing character array using for loop
print("Second array : ", end="   ")

for i in range(4):                       
   print(vals_char[i], end="   ")
print()

OUTPUT

First array :   3.4   6.5   7.6   8.9   
Second array :    a   i   o   u  

In the above example, we created two types of arrays and also performed their traversal.

Let’s see some functions which are in the array module:

  1. To count the number of elements in an array:
len( array_name )
  1. To calculate the size and address of an array:
array_name.buffer_info( )
  1. To reverse the array:
array_name.reverse( )

Below is the Implementation:

# Imported the array module
import array as arr  
                   
# Created a float array
vals_float = arr.array('d', [3.4, 6.5, 7.6, 8.9]) 

# to count the no. of elements in array
print("The length of the array is : ", end=" ")
print(len(vals_float))      
             
print("The address and the size of the array is : ", end=" ")

 # to calculate the size and address
print(vals_float.buffer_info())        

print("Original array :", end=" ")

# used the len() to calculate the length
for i in range(len(vals_float)):     
print(vals_float[i], end="  ")
print()

# function to reverse the array elements
vals_float.reverse()                 
print("Reversed array :", end=" ")
for i in range(len(vals_float)):
   print(vals_float[i], end="  ")
print()

OUTPUT

The length of the array is :  4
The address and the size of the array is :  (139725843707184, 4)
Original array : 3.4  6.5  7.6  8.9  
Reversed array : 8.9  7.6  6.5  3.4

This is just a glimpse of the array module, and there are many more functions.

FunctionDescription
array.append( var)Append a new element with value var at the end of the array.
array.buffer_info( )Returns a tuple with values of the current memory address and the length of an array.
array.count( var )Return the total occurrence of the passed number.
array.index( var )Returns the index of the required element.
array.insert( pos , value)Insert the element with the value var before the position.
array.pop( [pos] )Removes the element at the passed position and returns the element; if not found, returns -1
array.remove( var )Removes the first occurrence of the passed variable.
array.reverse( )Reverse the order of the array elements.
array.extend( iterable )Append items from iterable to the end of the array. If iterable is another array, it must have the same type code; if not, TypeError will be raised.

Try these methods on your own on CodeStudio for better clarity.

Taking the Input from the User

In Python, it is pretty simple to accept a single input from the user.

Syntax:

# Since, by default, it takes the string input, we need to typecast the input into our required data type
variable_name = input( )  

variable_name = data_type( input( ) ) 
                         OR
datatype( variable_name )

Before continuing with the array items, the length of the array must be known. So first, we will ask the user to specify the array’s length.

# Program to take the input as array from the user 
from array import *

# create the empty array
arr = array('i', [])
length = int(input("Enter the length of an array: \n"))

# For in loop for adding the elements in array one by one.
for i in range(length):
   x = int(input("Enter the next element: \n"))
   arr.append(x)
print("\nEntered array : ", end=" ")

# Direct accessing the elements from the array
for a in arr:
   print(a, end=" ")
print()

Input

Enter the length of an array: 
4
Enter the next element: 
76
Enter the next element: 
34
Enter the next element: 
76
Enter the next element: 
98

Output

Entered array :  76 34 76 98

In the above example, we used the integer input array. The components are supplied one by one by the user. Simultaneously, we appended each element to the arrays using the append() method.

What if we specify the floating type code and the user enters the integer values:

from array import *

# create the empty array, type specification is float
arr = array('d', [])   
length = int(input("Enter the length of an array: \n"))

# For in loop for adding the elements in array one by one.

for i in range(length):
   x = int(input("Enter the next element: \n"))
   arr.append(x)

print("\nEntered array : ", end=" ")

# Directly accessing the elements from the array
for a in arr:
   print(a, end=" ")
print()

INPUT

Enter the length of an array: 
3
Enter the next element: 
65
Enter the next element: 
87
Enter the next element: 
65

OUTPUT

Entered array :  65.0 87.0 65.0

Here, we specified the floating type Code, so automatically, the values get converted from Integral to the floating numbers.

Try to take another input from the user on your own.

Now, Let’s discuss the type of Arrays in python:

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.

illustrative_diagram

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:

from array import *                                    # array module
arr = array('u', ['c', 'o', 'd', 'e'], ['m', 'o', 'd', 'e'])   # 2-D array initialized
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.

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. 

Frequently Asked Questions

What is an array in Python?

An array is a data structure that stores values of the same data type. In Python, this is the main difference between arrays and lists. While python lists can contain values corresponding to different data types, arrays can only hold the same data type.

Are Arrays in Python mutable or not?

Since we can modify the array to change the size of dynamic arrays, arrays in python are mutable.

What is a 2D array in Python?

A two-dimensional array is an array within an array. In this type of array, the position of a data element is referred to by two indices instead of one.

What is the use of a 2D array?

The 2D array is arranged into matrices, which are collections of rows and columns. However, 2D arrays are designed to construct a data structure that resembles a relational database. It allows for storing a large amount of data at once, which can be given to any number of functions as needed.

Key Takeaways

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

You can also refer to these articles for more details on python programming language- Dictionary in python, Python Archives, Pattern Problems.

Happy Learning Ninja! 

By: Alisha Chhabra