Home »
Python
Accessing elements from the array in Python
By IncludeHelp Last updated : December 21, 2024
Prerequisites
Here are the examples to demonstrate how to access elements from the array
Example 1
# Accessing elements from the array
# importing array module
import array as arr
# int array
arr1 = arr.array('i', [10, 20, 30, 40, 50, 60])
# accessing element of array
print("arr1[0]: ", arr1[0])
print("arr1[3]: ", arr1[3])
# float array
arr2 = arr.array('d', [22.59, 33.32, 43.32])
# accessing elements of array
print("arr2[1]: ", arr2[1])
print("arr2[2]: ", arr2[2])
Output
arr1[0]: 10
arr1[3]: 40
arr2[1]: 33.32
arr2[2]: 43.32
Example 2
# importing array module
import array as arr
# declaring int array
arr = arr.array('i', [20, 40, 60, 80])
print("First element arr[0] :", arr[0])
print("Second element arr[1] :", arr[1])
print("Third element arr[2] :", arr[2])
print("Fourth element arr[1] :", arr[3])
print()
print("Last element arr[-1]:", arr[-1])
print("Second last element arr[-2]:", arr[-2])
Output
First element arr[0] : 20
Second element arr[1] : 40
Third element arr[2] : 60
Fourth element arr[1] : 80
Last element arr[-1]: 80
Second last element arr[-2]: 60