Table of Contents
ToggleAccessing an array items in Python refers to the process of retrieving the value stored at a specific index in the given array. Here, index is an numerical value that indicates the location of array items. Thus, you can use this index to access elements of an array in Python.
An array is a container that holds a fix number of items of the same type. Python uses array module to achieve the functionality like an array.
You can use the following ways to access array items in Python −
The process of accessing elements of an array through the index is known as Indexing. In this process, we simply need to pass the index number inside the index operator []. The index of an array in Python starts with 0 which means you can find its first element at index 0 and the last at one less than the length of given array.
import array as arr
# creating array
numericArray = arr.array('i', [111, 211, 311, 411, 511])
# indexing
print(numericArray[0])
print(numericArray[1])
print(numericArray[2])
Output:
111
211
311
In this approach, a block of code is executed repeatedely using loops such as for and while. It is used when you want to access array elements one by one.
import array as arr
# creating array
numericArray = arr.array('i', [111, 211, 311, 411, 511])
# iteration through for loop
for item in numericArray:
print(item)
Output:
111
211
311
411
511
The enumerate() function can be used to access elements of an array. It accepts an array and an optional starting index as parameter values and returns the array items by iterating.
import array as arr
# creating array
numericArray = arr.array('i', [111, 211, 311, 411, 511])
# use of enumerate() function
for loc, val in enumerate(numericArray):
print(f"Index: {loc}, value: {val}")
Output:
Index: 0, value: 111
Index: 1, value: 211
Index: 2, value: 311
Index: 3, value: 411
Index: 4, value: 511
In Python, to access a range of array items, you can use the slicing operation which is performed using index operator [] and colon (:).
This operation is implemented using multiple formats, which are listed below −
import array as arr
# creating array
numericArray = arr.array('i', [111, 211, 311, 411, 511])
# slicing operation
print(numericArray[2:])
print(numericArray[0:3])
Output:
array(‘i’, [311, 411, 511])
array(‘i’, [111, 211, 311])
Key Takeaway: Access array items with indexing, iteration, enumerate(), or slicing—powerful techniques to retrieve data exactly how you need it!
