Back to home
Logicmojo - Updated Sept 18, 2021

Arrays in Python are Data Structures that can hold multiple values of the same type. Often, they are misinterpreted as lists or Numpy Arrays. Technically, Arrays in Python are distinct from both these. So let’s go ahead, and see what are Arrays in Python and how to implement .

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).

When to use Array in Python?

Python arrays are used when you need to use many variables which are of the same type. It can also be used to store a collection of data. The arrays are especially useful when you have to process the data dynamically. Python arrays are much faster than list as it uses less memory.

Is Python list same as an Array?

Python Arrays and lists are store values in a similar way. But there is a key difference between the two i.e the values that they store. A list can store any type of values such as intergers, strings, etc. An arrays, on the other hand, stores single data type values. Therefore, you can have an array of integers, an array of strings, etc.

Creating an Array in Python

Arrays in Python can be created after importing the array module as follows –
β†’ import array as arr
The array(data type, value list) function takes two parameters, the first being the data type of the value to be stored and the second is the value list. The data type can be anything such as int, float, double, etc. Please make a note that arr is the alias name and is for ease of use. You can import without alias as well. There is another way to import the array module which is –

β†’ from array import *
This means you want to import all functions from the array module.

The following syntax is used to create an array.

  a=arr.array(data type,value list) #when you import using arr alias
 a=array(data type,value list) #when you import using *

Example: a=arr.array( β€˜d’ , [1.1 , 2.1 ,3.1] )
Here, the first parameter is β€˜d’ which is a data type i.e. float and the values are specified as the next parameter.
πŸ’‘ All values specified are of the type float. We cannot specify the values of different data types to a single array.

The following table shows you the various data types and their codes.

C TypePython Data TypeByte Size
signed charint1
unsigned charint1
signed shortint2
unsigned shortint2
signed longint4
unsigned longint4

Accessing array elements in Python

To access array elements, you need to specify the index values. Indexing starts at 0 and not from 1. Hence, the index number is always 1 less than the length of the array.


Array_name[index value]

import array as arr
a = arr.array('i', [2, 4, 6, 8])

print("First element:", a[0])
print("Second element:", a[1])
print("Last element:", a[-1])

Basic array operations

Finding the Length of an Array

Length of an array is the number of elements that are actually present in an array. You can make use of len() function to achieve this. The len() function returns an integer value that is equal to the number of elements present in that array.

β†’ len(array_name)

  a=arr.array('d', [1.1 , 2.1 ,3.1] )
 Output - 3

Adding/ Changing elements of an Array

We can add value to an array by using the append(), extend() and the insert (i,x) functions. The append() function is used when we need to add a single element at the end of the array.

  a=arr.array('d', [1.1 , 2.1 ,3.1] )
 Output - array(β€˜d’, [1.1, 2.1, 3.1, 3.4])

The resultant array is the actual array with the new value added at the end of it. To add more than one element, you can use the extend() function. This function takes a list of elements as its parameter. The contents of this list are the elements to be added to the array.

  a=arr.array('d', [1.1 , 2.1 ,3.1] )
 Output - array(β€˜d’, [1.1, 2.1, 3.1, 4.5, 6.3, 6.8])

The resulting array will contain all the 3 new elements added to the end of the array.However, when you need to add a specific element at a particular position in the array, the insert(i,x) function can be used. This function inserts the element at the respective index in the array. It takes 2 parameters where the first parameter is the index where the element needs to be inserted and the second is the value.

  a=arr.array('d', [1.1 , 2.1 ,3.1] )
 Output - array(β€˜d’, [1.1, 2.1, 3.8, 3.1])

The resulting array contains the value 3.8 at the 3rd position in the array.

Removing/ Deleting elements of an array:

Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not. The pop() function takes either no parameter or the index value as its parameter. When no parameter is given, this function pops() the last element and returns it. When you explicitly supply the index value, the pop() function pops the required elements and returns it.

  a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])
 Output - 4.6

The first pop() function removes the last value 4.6 and returns the same while the second one pops the value at the 4th position which is 3.1 and returns the same.

The remove() function, on the other hand, is used to remove the value where we do not need the removed value to be returned. This function takes the element value itself as the parameter. If you give the index value in the parameter slot, it will throw an error.

  a=arr.array('d',[1.1 , 2.1 ,3.1])
 Output - array(β€˜d’, [2.1,3.1])

The output is an array containing all elements except 1.1.

Slicing Python Arrays

We can access a range of items in an array by using the slicing operator :.

import array as arr

numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]
numbers_array = arr.array('i', numbers_list)

print(numbers_array[2:5]) # 3rd to 5th
print(numbers_array[:-5]) # beginning to 4th
print(numbers_array[5:])  # 6th to end
print(numbers_array[:])   # beginning to end


array('i', [62, 5, 42])
array('i', [2, 5, 62])
array('i', [52, 48, 5])
array('i', [2, 5, 62, 5, 42, 52, 48, 5])

Looping through an array:

Using the for loop, we can loop through an array.

a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])
print("All values")
for x in a: 
   print("specific values")
for x in a[1:3]: 

Reversing the Elements

You can reverse the order of elements by using the reverse() method.

from array import * 
arr1 = array('i', [1,2,3,4,5])

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

Python Lists Vs Arrays

In Python, we can treat lists as arrays. However, we cannot constrain the type of elements stored in a list. For example:

  # elements of different types
 a = [1, 3.5, "Hello"]

If you create arrays using the array module, all elements of the array must be of the same numeric type.

  import array as arr
 # Error
 a = arr.array('d', [1, 3.5, "Hello"])


Although knowing how to deal with arrays isn’t a mandatory part of learning Python, able to do so is surely an added advantage. This is especially true when dealing with churning out arrays and matrices. Nonetheless, lists in Python are way much more flexible than arrays. Unlike arrays, lists are able to store elements belonging to different data types and are faster. Typically, the array module is required for interfacing with C code. It is typically advised to avoid using arrays in Python. However, that doesn’t mean that you can’t learn them. You can also refer to python interview questions for further concepts

Good Luck & Happy Learning!!