How to access elements from an array in Python

Overview

An array in Python is used to store multiple values or items or elements of the same type in a single variable.

We can access elements of an array using the index operator []. All you need do in order to access a particular element is to call the array you created. Beside the array is the index [] operator, which will have the value of the particular element’s index position from a given array.

Note that the value you pass into the index operator (the index position of the element you wish to access) must be an integer.

Example

# importing the array module
import array as arr
# creating an integer datatype array
x = arr.array('i', [1,2,3,4,5,6,7])
# to access the index 3 element
print('The element in the index 3 of the array is: ', x[3])
# creating a float datatype array]
y = arr.array('d', [1.5, 2.7, 3.5, 8.2, 6.9])
# to access the index 0 or the first element of the array
print('The element of the array in the index 0 of the float array is: ', y[0])

It is worth noting that in Python, the first character of a list, string, array etc., is of index 0.