Python Array Indexing (original) (raw)

Last Updated : 23 Jul, 2025

Python arrays are zero-indexed, just like Lists. First element is at index 0, the second at index 1 and so on. Let's see how indexing works with arrays using array module:

Access Array Element with Index

We can access elements from the beginning of the array using positive indices:

Python `

import array

Create an array of integers using the 'i' type code

arr = array.array('i', [10, 20, 30, 40, 50])

Accessing elements using indexing

print(arr[0])
print(arr[1])
print(arr[4])

`

Let's explore python array indexing in detail:

Table of Content

Negative Array Indexing

In Python, arrays support negative indexing where the last element of the array is accessed with index -1, the second-to-last element with index -2 and so on. Here's an example:

Python `

import array

Create an array of integers

arr = array.array('i', [10, 20, 30, 40, 50])

Accessing elements using negative indexing

print(arr[-1]) print(arr[-2])

`

**Explanation:

Negative indexing allows us to quickly access elements at the end of the array without needing to know its length.

2D Array Indexing

In a 2D array, elements are arranged in rows and columns. We can access elements using two indices: one for the row and one for the column.

Python `

import array

Creating a 2D array (array of arrays)

arr = array.array('i', [array.array('i', [1, 2, 3]), array.array('i', [4, 5, 6]), array.array('i', [7, 8, 9])])

Accessing elements in the 2D array

print(arr[0][0]) # (first element of first row) print(arr[1][2]) # (third element of second row) print(arr[2][1]) # (second element of third row)

`

**Explanation:

3D Array Indexing

In a 3D array, elements are arranged in 2D grids and those grids are nested inside another array. You can access an element using three indices: one for the 2D array, one for the row and one for the column.

Python `

import array

Creating a 3D array (array of arrays of arrays)

arr = array.array('i', [ array.array('i', [array.array('i', [1, 2, 3]), array.array('i', [4, 5, 6]), array.array('i', [7, 8, 9])]), array.array('i', [array.array('i', [10, 11, 12]), array.array('i', [13, 14, 15]), array.array('i', [16, 17, 18])]), ])

Accessing elements in the 3D array

print(arr[0][0][0]) print(arr[1][2][1]) print(arr[1][0][2])

`

**Explanation:

Array Slicing using Index range

Array slicing allows us to extract a subarray (a portion of the original array) by specifying a range of indices. Here’s an example of slicing:

Python `

import array

Create an array of integers

arr= array.array('i', [10, 20, 30, 40, 50, 60, 70])

Slice the array

print(arr[1:5])
print(arr[::2])
print(arr[-4:-1])

`

**Explanation: