How to define a two-dimensional array in Python?

To define a two-dimensional (2D) array (or matrix) in Python, you can use nested lists, the array module, or the numpy library (most powerful for numerical work). Below is a detailed explanation with examples for each method.

1. Using Nested Lists (Most Common Method)

Python lists are flexible and commonly used to represent 2D arrays. Each inner list represents a row.

Example 1: Initialize a 2D List

# Define a 2x3 matrix
matrix = [
    [1, 2, 3],
    [4, 5, 6]
]

print(matrix)  # Output: [[1, 2, 3], [4, 5, 6]]

Example 2: Access/Modify Elements

# Access element at row 0, column 1
print(matrix[0][1])  # Output: 2

# Modify element at row 1, column 2
matrix[1][2] = 99
print(matrix)  # Output: [[1, 2, 3], [4, 5, 99]]

Example 3: Initialize with Zeros

rows = 3
cols = 2

# Safe method (avoves aliasing)
zero_matrix = [[0 for _ in range(cols)] for _ in range(rows)]
print(zero_matrix)  # Output: [[0, 0], [0, 0], [0, 0]]

# Unsafe method (aliasing issues)
bad_matrix = [[0] * cols] * rows  # All rows reference the same inner list!
bad_matrix[0][0] = 5
print(bad_matrix)  # Output: [[5, 0], [5, 0], [5, 0]] (all rows modified)

2. Using the array Module (Less Common)

The array module provides typed arrays, but it’s 1D. To create a 2D structure, nest arrays inside a list.

Example:

from array import array

# Create a list of arrays
matrix = [
    array('i', [1, 2, 3]),  # 'i' = integer type
    array('i', [4, 5, 6])
]

print(matrix[0][1])  # Output: 2

Limitations:

  • Not as flexible as lists for mixed data types.
  • Requires all elements to be of the same type.

3. Using NumPy (Best for Numerical Work)

The numpy library provides efficient multidimensional arrays and is ideal for mathematical operations.

Example 1: Create a NumPy 2D Array

import numpy as np

# From a nested list
matrix = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

print(matrix)
# Output:
# [[1 2 3]
#  [4 5 6]]

Example 2: Initialize with Zeros/Ones

# 3x2 matrix of zeros
zero_matrix = np.zeros((3, 2))
print(zero_matrix)
# Output:
# [[0. 0.]
#  [0. 0.]
#  [0. 0.]]

# 2x3 matrix of ones
ones_matrix = np.ones((2, 3))
print(ones_matrix)
# Output:
# [[1. 1. 1.]
#  [1. 1. 1.]]

Example 3: Access/Modify Elements

# Access element at row 1, column 2
print(matrix[1, 2])  # Output: 6

# Modify a slice
matrix[0:2, 1] = 99  # Set column 1 of all rows to 99
print(matrix)
# Output:
# [[ 1 99  3]
#  [ 4 99  6]]

4. Common Operations

Iterate Over Rows and Columns:

# Using nested loops
for row in matrix:
    for element in row:
        print(element, end=" ")
    print()

Get Dimensions:

# For nested lists
rows = len(matrix)
cols = len(matrix[0]) if rows > 0 else 0

# For NumPy arrays
rows, cols = matrix.shape

Key Differences

MethodUse CaseProsCons
Nested ListsGeneral-purpose, mixed data typesFlexible, no extra librariesSlower for large datasets
array ModuleHomogeneous data, memory efficiencyMore efficient than listsLimited to 1D without nesting
NumPyNumerical/mathematical operationsFast, optimized, rich functionsRequires installing numpy

Full Example: Matrix Multiplication with NumPy

import numpy as np

matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])

result = np.dot(matrix_a, matrix_b)  # Matrix multiplication
print(result)
# Output:
# [[19 22]
#  [43 50]]

Common Pitfalls

  1. Aliasing in Nested Lists:
    Avoid initializing with [[0]*cols]*rows (all rows reference the same list). Use list comprehensions instead.
  2. Mixed Data Types in NumPy:
    NumPy arrays cast all elements to the same type (e.g., [[1, 2.5]] becomes float).

Summary

  • Use nested lists for simple, small, or mixed-type 2D arrays.
  • Use NumPy for numerical work, large datasets, or mathematical operations.
  • Use the array module sparingly (better suited for 1D data).

Leave a Reply

Your email address will not be published. Required fields are marked *