Accessing Array Items in Python: Indexing and Iteration
Learn how to access array items in Python using indexing, iteration, and the enumerate() function. This guide covers retrieving values at specific indices and demonstrates how to work with Python arrays effectively with examples and code snippets.
Accessing Array Items in Python
Accessing array items in Python means retrieving the value stored at a specific index in the array. The index is a numerical value indicating the location of array items. You can use this index to access elements of an array.
An array is a container holding a fixed number of items of the same type. Python uses the array
module to achieve functionality like an array.
Ways to Access Array Items in Python
You can access array items in Python using:
- Indexing
- Iteration
- enumerate() function
Using Indexing
Indexing means accessing elements of an array through their index. Pass the index number inside the index operator []
. The index of an array in Python starts at 0.
Example
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
Using Iteration
In this approach, a block of code is repeatedly executed using loops such as for
and while
. It is used when you want to access array elements one by one.
Example
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
Using enumerate() function
The enumerate()
function can be used to access elements of an array. It accepts an array and an optional starting index as parameters and returns the array items by iterating.
Example
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
Accessing a Range of Array Items in Python
To access a range of array items, use the slicing operation with the index operator []
and colon :
.
Slicing formats:
[:index]
- From beginning to desired range[:-index]
- From end to desired range[index:]
- From specific index number to the end[start index : end index]
- Within a range (optional increment after end index)
Example
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])