Index and index method in Array – Python

Array is a most fundamental and memory efficient data structure in Python Programming Language. Arrays are indexed and its elements can be accessed based on their index positions. Arrays can achieve O(1) time complexity for accessing elements by index. Elements in array can be accessed and updated based on their index positions.

Element at index in Array

Elements in an array are stored sequentially based on their index positions. Specific size (number of elements) is defined when an array object is created. Memory allocation and index positions are based on the defined number of elements.

Array elements are assigned index in two ways:

  1. Index from left to right (Positive Indexing)
  2. Index from right to left (Negative Indexing)
Array Indexing
Array Indexing

Index from left to right (Positive Indexing)

Index of an element in the array starts from left to right. First element from left is assigned index 0 and then index increased one at a time in the right direction. The right most element i.e. last element of array will have index = number of elements in array -1. This indexing from left to right also known as Positive Indexing.

Index from right to left (Negative Indexing)

Index of an element in array can also starts from right to left. Right most element i.e. last element is assigned index -1 and then index decreased one-by-one in the left direction. The left most element i.e. first element of the array will have index = negative of number of element in array. This indexing from right to left also known as Negative Indexing.

Access and update element – Positive Indexing

Elements from an array can be accessed and updated based on their positive index positions.

# positive indexing - access and update element in array
print("positive indexing - array of integer type - update integer")

import array as array     # import array module

integer_array = array.array("i", [10, 20, 30, 40, 50])   # defined array with type-code i (integer)
print(integer_array)

print("element at index 3 = ", integer_array[3])   # access element at index 3

integer_array[3] = 70     # update element at index 3

print("updated element at index 3 = ", integer_array[3])   # access element at index 3

Following steps are followed in this program.

  1. Import array module
  2. Using array() method, declare and initialize an array with type-code i (signed integer) and reference by variable integer_array.
  3. integer_array[3] – Access element at index 3 from array. It should return 40 from the array.
  4. integer_array[3] = 70 – Update element at index 3 in the array. It will update element 40 with 70.
  5. integer_array[3] – Again, access element at index 3 from array. It should return 70 from the updated array.

Program Output

positive indexing - array of integer type - update integer
array('i', [10, 20, 30, 40, 50])
element at index 3 =  40
updated element at index 3 =  70

From the output, originally element 40 was their at index position 3 and after update element 70 comes at index position 3.

Access and update element – Negative Indexing

Similar to positive indexing, elements from an array can be accessed and updated based on their negative index positions.

# negative indexing - access and update element in array
print("negative indexing - array of integer type - update integer")

import array as array   # import array module

integer_array = array.array("i", [10, 20, 30, 40, 50])   # defined array with type-code i (integer)
print(integer_array)

print("element at index -3 = ", integer_array[-3])   # access element at negative index -3
integer_array[-3] = 70   # update element at index -3
print("updated element at index -3 = ", integer_array[-3])   # access element at negative index -3

Following steps are followed in this program.

  1. Import array module
  2. Using array() method, declare and initialize an array with type-code i (signed integer) and reference by variable integer_array.
  3. integer_array[-3] – Access element at index -3 from array. It should return 30 from the array.
  4. integer_array[3] = 70 – Update element at index -3 in the array. It will update element 30 with 70.
  5. integer_array[3] – Again, access element at index -3 from array. It should return 70 from the updated array.

Program Output

negative indexing - array of integer type - update integer
array('i', [10, 20, 30, 40, 50])
element at index -3 =  30
updated element at index -3 =  70

From the output, originally element 30 was their at index position -3 and after update element 70 comes at index position -3.

IndexError: array index out of range

  • Positive index => Left to Right => 0 to number of elements in array -1
  • Negative index => Right to Left => -1 to negative of number of elements in array

If the accessed or updated index position is not present, then we will get IndexError.

# IndexError - access element in array
print("IndexError - access element in array")

import array as array   # import array module

integer_array = array.array("i", [10, 20, 30, 40, 50])  # defined array integer, index from 0 to 4
print(integer_array)

print("element at index 5 = ", integer_array[5])  # access element at index 5
  • We have declared and initialized an array integer_array with type-code i (signed integer). This array has 5 elements.
  • integer_array positive index (left to right) from 0 to 4
  • integer_array negative index (right to left) from -1 to -5
  • Access element at index 5. Index 5 does not present in the array. This will give an IndexError.

Program Output

IndexError - access element in array
array('i', [10, 20, 30, 40, 50])
Traceback (most recent call last):
  File "D:\update-element-array.py", line 29, in <module>
    print("element at index 5 = ", integer_array[5])
                                   ~~~~~~~~~~~~~^^^
IndexError: array index out of range

From the output, since index 5 does not exists in array, it gives an error. IndexError: array index out of range.

index() method

Previously, we access and updated element based on their index position. In those scenarios, we knew the element index position which we want to access. Python provides built-in index() method to get the index position of an element. Syntax of index() method:

index_position = array_object.index(element)

  • array_object is an array (specific to type-code) in which we want to get the index of an element.
  • index is the name of the method
  • element is the element for which index position to found out.
  • index_position is the returned positive index position in the array for the given element. If element will not be present in array, then it will throw ValueError.

index() – index of an element

# array of double type - index of an element
print("array of double type - index of an element")

import array as array    # import array module

double_array = array.array("d", [14.232, 27.3, 30.34, 49.87])  # define array with type-code d (double)
print(double_array)

index = double_array.index(30.34)   # index() method to get index of an element
print("index of element 30.34 = ", index)

In this program, we have import array module. We have declared and initialized an array double_array with type-code d (double). We are using double_array.index(30.34) to get index position of element in the array.

Program Output

array of double type - index of an element
array('d', [14.232, 27.3, 30.34, 49.87])
index of element 30.34 =  2

From the output – In the array, index of element 30.34 = 2

index() method – element not in array

# index method - element not in array
print("index method - element not in array")

import array as array    # import array module

integer_array = array.array("i", [10, 20, 30, 40, 50])   # define array with type-code i (signed integer)
print(integer_array)

index = integer_array.index(60.54)   # index() method to get index of an element

In this program, we have import array module. We have declared and initialized an array integer_array with type-code i (signed integer). We are using integer_array.index(60.54) to get index position of element in the array. If the element does not exists in the array, then it will raise ValueError.

Program Output

index method - element not in array
array('i', [10, 20, 30, 40, 50])
Traceback (most recent call last):
  File "D:\index-element-array.py", line 20, in <module>
    index = integer_array.index(60.54)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: array.index(x): x not in array

Since the element 60.54 does not exist in array, we got an error => ValueError: array.index(x): x not in array

Custom implementation – index() method

We have seen how built-in index() method works. We can write our own code to get the index of an element from an array.

# custom_index of an element
print("custom_index of an element")

import array as array         # import array module

def custom_index(array_object, element):    # definition of custom_index
	for index_iter in range(len(array_object)):
		if array_object[index_iter] == element:
			return index_iter
	raise ValueError("custom_index(arr, x): x not in arr")

integer_array = array.array("i", [10, 20, 30, 40, 50])
print(integer_array)
index = custom_index(integer_array, 40)
print("index of element 40 = ", index)

Lets understand the step by step implementation of this program.

  • We are importing array module. This is to create and read the original array object.
  • We are defining a method custom_index(array_object, element), this method will take two arguments array_object => original array object in which we will look for index position of given element, element to get its index position
  • Using for loop and range() method, iterate through the index positions of an array.
  • Add logic (if conditions) to check if current element is equal to the given element.
  • If element found in array, return that positive index. Otherwise keep iterating for all the elements of array.
  • If not element in array matched with given element, raise ValueError
  • Assign returned index to variable index and print its value.
  • For example => we are passing an array with type-code i (signed integer) and getting an index of element 40, which should be found at index 3.

Program Output

custom_index of an element
array('i', [10, 20, 30, 40, 50])
index of element 40 =  3

Summary

In this article we learned to access and update elements of an array based on index positions. We also learned about index() method and custom implementation for that method. Following scenarios were discussed:

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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