Python Access Array Item
In Python, arrays can be used as an alternative to lists when we need more efficient storage of data. In this article, we will explore how to access array items using the array module in Python.
Once array is created, we can access its items just like accessing elements in a list. Here are some ways to access array items:
Accessing Elements by Index
Arrays in Python are zero-indexed. The first element is at index 0, the second at index 1 and so on. You can access elements of an array using their index:
import array
# Creating an array of integers
arr = array.array('i', [10, 20, 30, 40, 50])
# Accessing elements by index
print(arr[0])
print(arr[1])
print(arr[2])
Let's explore other methods of accessing elements by index in python:
Table of Content
Accessing Elements from End
We can also access elements from the end of the array using negative indices. A negative index counts from the last element, where -1 represents the last element, -2 represents the second-to-last and so on:
import array
# Creating an array of integers
arr = array.array('i', [10, 20, 30, 40, 50])
# Accessing elements from the end
print(arr[-1]) # (last element)
print(arr[-2]) # (second to last element)
Slicing Arrays to Get Subset
Just like lists, we can slice arrays to access a subset of elements. The slice syntax allows us to specify a start index, an end index and an optional step:
import array
# Creating an array of integers
arr = array.array('i', [10, 20, 30, 40, 50])
# Slicing the array
print(arr[1:4])
Iterating Through Array Items
We can also iterate over the elements of an array using a loop. This is useful when we want to perform some operation on each item:
import array
# Creating an array of integers
arr = array.array('i', [10, 20, 30, 40, 50])
# Iterating through the array
for i in arr:
print(i)
Using index() to Find an Item
If we need to find the index of a specific item in the array, we can use the index() method. This method returns the index of the first occurrence of the item:
import array
# Creating an array of integers
arr = array.array('i', [10, 20, 30, 40, 50])
# Finding the index of an item
idx = arr.index(30)
print(idx) # (index of 30)
Modifying Array Items
We can modify the value of an element in an array by accessing it via its index and assigning a new value:
import array
# Creating an array of integers
arr = array.array('i', [10, 20, 30, 40, 50])
# Modifying an element
arr[2] = 35
print(arr)
Checking If an Item Exists in the Array
We can use the in operator to check if an item exists in an array. This will return True if the item is found and False if it's not:
import array
# Creating an array of integers
arr = array.array('i', [10, 20, 30, 40, 50])
# Checking if an item exists in the array
print(30 in arr)
print(60 in arr)