← Back to NumPy Course | Chapter 4: Indexing & Slicing | Lesson 2 of 7

2D indexing

Two numbers, row then column, select a single cell in a table.

In this page:

  1. 2D indexing
Syntax
python
arr[row, col]

2D indexing

Use arr[row, col] to reach one element of a 2-D array. This comma form is faster and clearer than chained arr[row][col]. A single index such as arr[1] returns the whole row.

Note: Both arr[1][2] and arr[1, 2] work, but the comma version does one lookup instead of two.

Example: 2D indexing

python
import numpy as np

m = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(m[1, 2])
print(m[0])
print(m[2][0])

# Output:
# 6
# [1 2 3]
# 7
Related Topics
Common Mistakes
  1. Swapping row and column order
  2. Using chained indexing when assigning to slices
  3. Expecting arr[1] to return a single value
Chapter Summary
  • Use arr[row, col]
  • One index returns a whole row
  • Rows come first then columns
  • Comma indexing is preferred
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.