Introduction to Arrays

Arrays are one of the most popular and quite fundamental data structures in most programming languages. Let’s consider an example to understand the concept of an array. Suppose there are ten students in a class having student ids from 0 to 9, and you need to store their scores. Later on, you may need to perform various operations on it, such as computing the class’s average. This can be done by creating ten different variables. But this is an efficient approach because you are writing a lot of redundant code, and it will not be practical when performing operations on the data. This is where the usage of Array comes in place.

Without Arrays

StudentId0; 
StudentId1; 
StudentId2; 
StudentId3; 
StudentId4; 
StudentId5; 
StudentId6; 
StudentId7; 
StudentId8; 
StudentId9; 

With Arrays

StudentId[9];

What is an Array?

An array is a data structure that can store multiple items of the same type. It means that you will have a single variable that can contain a collection of homogeneous items. For example, we can store the marks of the ten students in a single variable. It will make our code concise, simple, and efficient. We can efficiently perform operations on the data, such as computing the average.

Arrays in Memory

Note that an array contains items of the same type, which means that you cannot store a float number in an array of the integer type. Moreover, items of an array are held at contiguous locations in the RAM (Random Access Memory).

As you can see in the above figure, elements in an array are stored consecutively. We have five integer type items; the first item is located at the address 0x0400. (Note that hexadecimal numbers represent addresses in memory). Here, each integer is of 4 bytes, and therefore, the next item is at the location 0x0404 (an offset of 4). Moreover, in actuality, elements are stored by their binary representation. The above figure shows the decimal representation for simplicity and understanding purposes.

Access Array Elements

Suppose we have an array arr. We can access its elements by their indexes. In many programming languages, arrays start with index 0, so the first item has index 0, the second item has index 1, and so on. If we have n number of elements in an array, then the last element’s index will be n-1. Moreover, the length of an array is defined as the number of items contained in it. Consider the following figure.

Example of Arrays

Consider the following code:

import array
arr = array.array("i", [9, 7, 8, 6, 9])

The above declares an array of integer Data Type, with five initial elements.

Now let’s access the elements at different positions:

print("ELement at the index 0:", str(arr[0]))
print("ELement at the index 2:", str(arr[2]))
print("ELement at the index 4:", str(arr[4]))

Output

Element at index 0: 9

Element at index 2: 8

Element at index 4: 9

Various operations can be performed on an array, such as insert, delete, update an item, etc.

Let’s have a look at some of the most used operations.

Traverse an Array

To traverse the complete array (access all the elements), we can loop through it.

for item in arr:
    print(item)

9
7
8
6
9

append()

To add an element at the end of an array, use the arr.append(x) method, where x is the item to be inserted, and arr is the created array.

import array

arr = array.array("i", [9, 7, 8, 6, 9])
arr.append(5)
# print the array items
for item in arr:
    print(item)

9
7
8
6
9
5

In the above example, we add 5 at the end of the array. As you can see in the output, 5 got added.

insert()

While the append() method adds an element at the end of an array, the insert() method can insert an item at any index. The syntax is arr.insert(i, x), where x is the item inserted at position i.

import array

arr = array.array("f", [9.3, 17, 1.8, 0.6, 9])

#inserts 0.5 at the index 3
arr.insert(3, 0.5)
# print the array items
for item in arr:
    print(f"{item:.1f}")

Output

9.3
17.0
1.8
0.5
0.6
9.0

In the above example, we insert 0.5 at position 3 to an array of the float type. When we add an item at an index, the rest of the elements get shifted to the right. Therefore, 6 will now be at index 4.

pop()

The arr.pop() method removes the last item from an array by default. However, you can provide an index to remove the element at a specific position. This function returns the deleted element.

import array

arr = array.array("u", ["a", "b", "c","d","e"])
#delete the last element
deleted_item = arr.pop()
print("Deleted item:",str(deleted_item))

#delete the element at the index 2
deleted_item = arr.pop(2)
print("Deleted item:",str(deleted_item))

# print the final array
for item in arr:
    print(item)

Output

Deleted item: e

Deleted item: c

a

b

d

In the above example, we delete the last item first, and then we delete the element at index 2. Finally, we display the updated array.

remove()

The arr.pop() method takes the index to delete an item located at that position. The arr.remove() method, on the other hand, takes the item to be deleted and not the index. If there are multiple items with the same value, it will only remove its first occurrence.

import array

arr = array.array("i", [9, 7, 8, 6, 9])
#delete 9 from the array
arr.remove(9)

# print the final array
for item in arr:
    print(item)

Output

7

8

6

9

As you see in the above output, arr. remove() only deletes the first occurrence of 9.  If the specified element does not exist, the method will throw a ValueError.

arr.remove(0)

Output

arr.remove(0)

ValueError: array.remove(x): x not in list

index()

To find the index of an element, use the arr.index(x) method. This method finds the first occurrence only. 

import array
arr = array.array("i", [9, 7, 8, 6, 9])
index = arr.index(8)
print("The element is found at the index:", str(index))

The element is found at the index: 2

This Function throws a ValueError if the element is not present.

count()

The arr.count(x) method returns the number of times x occurs in the array arr.

import array
arr = array.array("i", [9, 7, 8, 6, 9])
count = arr.count(9)
print("Number of occurrences of 9:", str(count))
count = arr.count(0)
print("Number of occurrences of 0:", str(count))

Output

Number of occurrences of 9: 2

Number of occurrences of 0: 0

Update

If you want to update the value at a particular position, access it first, then assign the new value.

import array
arr = array.array("u", ["a", "b", "c", "d", "e"])
arr[4]='y'
# print the final array
for item in arr:
    print(item)

Output

a

b

c

d

y

In the above example, we change the item’s value at index 4 from e to y.

 

Back to: Data Structure > Data Structure - Arrays

Leave a Reply

Your email address will not be published. Required fields are marked *