Last modified: Mar 25, 2026 By Alexander Williams

Python 2D Arrays Guide: Lists, NumPy, Examples

A 2D array is a grid of data. It has rows and columns. Think of it like a spreadsheet or a chessboard. In Python, we often call this a matrix.

Understanding 2D arrays is crucial. They are used in game boards, image processing, and scientific data. This guide will show you how to work with them.

What is a 2D Array?

A 2D array is a collection of items. These items are arranged in two dimensions. The first dimension is the row. The second dimension is the column.

Each cell in the grid can hold a value. You access a cell using two indices. The first index is for the row. The second index is for the column.

Python does not have a built-in 2D array type. But we can create them easily. The most common ways are using nested lists or the NumPy library.

Creating 2D Arrays with Nested Lists

The simplest method is a list of lists. Each inner list represents a row in the 2D array.


# Creating a 2D array (3 rows, 4 columns) using nested lists
matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]
print("2D Array (List of Lists):")
print(matrix)
    

2D Array (List of Lists):
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
    

You can also create it dynamically. Use a list comprehension. This is efficient for large arrays.


# Create a 4x4 matrix initialized with zeros
rows, cols = 4, 4
dynamic_matrix = [[0 for j in range(cols)] for i in range(rows)]
print(dynamic_matrix)
    

Accessing and Modifying Elements

Use double indexing to get a value. The syntax is array[row_index][column_index]. Indices start at 0.


matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Access the element in the second row, third column (row=1, col=2)
element = matrix[1][2]
print(f"Element at [1][2]: {element}")

# Modify the element in the first row, first column
matrix[0][0] = 99
print("Modified Matrix:")
for row in matrix:
    print(row)
    

Element at [1][2]: 6
Modified Matrix:
[99, 2, 3]
[4, 5, 6]
[7, 8, 9]
    

Iterating Through a 2D Array

You often need to loop through all elements. Use nested for loops. The outer loop goes through rows. The inner loop goes through columns.


matrix = [[10, 20], [30, 40], [50, 60]]

print("Iterating with nested loops:")
for i in range(len(matrix)):          # Loop through rows
    for j in range(len(matrix[i])):   # Loop through columns in row i
        print(f"matrix[{i}][{j}] = {matrix[i][j]}")
    

You can also use a simpler loop. Just iterate through each row list directly.


print("\nIterating directly over rows and items:")
for row in matrix:
    for item in row:
        print(item, end=' ')
    print()  # Newline after each row
    

Common Operations on 2D Lists

You can perform many operations. These include finding dimensions, transposing, and flattening.

To get the number of rows and columns:


matrix = [[1, 2, 3], [4, 5, 6]]
num_rows = len(matrix)
num_cols = len(matrix[0]) if matrix else 0  # Handle empty matrix
print(f"Rows: {num_rows}, Columns: {num_cols}")
    

Transposing swaps rows and columns. Use a list comprehension with zip(*matrix).


original = [[1, 2], [3, 4], [5, 6]]
transposed = [list(row) for row in zip(*original)]
print("Original:", original)
print("Transposed:", transposed)
    

Using NumPy for Powerful 2D Arrays

For numerical work, use NumPy. It is a fast library for arrays. NumPy arrays are more efficient than lists.

First, you need to install NumPy. Use the command pip install numpy. Then import it in your code.


import numpy as np

# Create a 2D NumPy array
np_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("NumPy 2D Array:")
print(np_array)
print(f"Shape: {np_array.shape}")  # Shows (rows, columns)
print(f"Data type: {np_array.dtype}")
    

NumPy makes operations easy. You can do element-wise math. You can also get rows and columns simply.


# Access the entire second row (index 1)
row = np_array[1, :]
print(f"Second row: {row}")

# Access the entire first column (index 0)
column = np_array[:, 0]
print(f"First column: {column}")

# Perform scalar multiplication
result = np_array * 2
print("Array multiplied by 2:")
print(result)
    

For more on installing packages, see our guide on using pip.

When to Use Lists vs. NumPy

Choose nested lists for simple, small grids. They are part of core Python. No extra installation is needed.

Choose NumPy for heavy numerical computation. It is faster for large datasets. It also has many built-in functions.

If you are working in data science, NumPy is essential. It integrates with libraries like Pandas and Matplotlib. Learn more about Python for data science.

Practical Example: Game Board

Let's model a Tic-Tac-Toe board. We use a 3x3 2D array. We can print it and check for a winner.


def print_board(board):
    """Prints the Tic-Tac-Toe board in a readable format."""
    for row in board:
        print(" | ".join(row))
        print("-" * 9)

# Initialize an empty 3x3 board
tic_tac_toe = [[' ' for _ in range(3)] for _ in range(3)]

# Make some moves
tic_tac_toe[0][0] = 'X'
tic_tac_toe[1][1] = 'O'
tic_tac_toe[2][2] = 'X'

print("Tic-Tac-Toe Board:")
print_board(tic_tac_toe)
    

Tic-Tac-Toe Board:
X |   |
---------
  | O |
---------
  |   | X
    

Conclusion

2D arrays are fundamental in Python programming. You can create them with nested lists. For advanced math, use NumPy arrays.

Remember how to access elements with two indices. Practice iterating with loops. Understand the difference between lists and NumPy.

This knowledge is key for many applications. These include games, data analysis, and image processing. Start by experimenting with the code examples above. Check out our tutorial on basic Python loops to strengthen your fundamentals.