Python 2D Array
Complete guide to two-dimensional arrays in Python
What is a 2D Array in Python?
Definition: A 2D array (two-dimensional array) is a data structure that stores
elements in a grid-like format with rows and columns. In Python, 2D arrays can be implemented
using nested lists or NumPy arrays.
Think of a 2D array as a table or matrix where each element is accessed using two indices: one for the row and one for the column.
Creating 2D Arrays
Method 1: Using Nested Lists
# Create a 3x3 2D array
array_2d = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Or in one line
array_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]Method 2: Using List Comprehension
# Create a 4x5 array filled with zeros
rows, cols = 4, 5
array_2d = [[0 for _ in range(cols)] for _ in range(rows)]
# Create with sequential numbers
array_2d = [[i*cols + j for j in range(cols)] for i in range(rows)]
Warning: Avoid using
[[0] * cols] * rows as it creates shallow
copies. All rows will reference the same list!
Method 3: Using NumPy
import numpy as np
# Create from list
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
# Create zeros array
zeros = np.zeros((3, 4)) # 3 rows, 4 columns
# Create ones array
ones = np.ones((2, 5))
# Create identity matrix
identity = np.eye(4)
# Create with random values
random_array = np.random.randint(0, 10, size=(3, 3))Accessing Elements
array_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Access single element (row 1, column 2)
element = array_2d[1][2] # Returns 6
# Access entire row
row = array_2d[0] # Returns [1, 2, 3]
# Access column (requires iteration or list comprehension)
column = [row[1] for row in array_2d] # Returns [2, 5, 8]
# With NumPy (much easier)
import numpy as np
np_array = np.array(array_2d)
column = np_array[:, 1] # Returns [2, 5, 8]Modifying Elements
array_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Modify single element
array_2d[1][1] = 99 # Changes 5 to 99
# Modify entire row
array_2d[0] = [10, 20, 30]
# Modify column (requires iteration)
for i in range(len(array_2d)):
array_2d[i][2] = 0 # Set all elements in column 2 to 0Iterating Through 2D Arrays
Method 1: Nested Loops
array_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Iterate through all elements
for row in array_2d:
for element in row:
print(element, end=' ')
print() # New line after each row
# With indices
for i in range(len(array_2d)):
for j in range(len(array_2d[i])):
print(f"[{i}][{j}] = {array_2d[i][j]}")Method 2: Using enumerate()
for i, row in enumerate(array_2d):
for j, element in enumerate(row):
print(f"Position ({i},{j}): {element}")Common Operations
Get Dimensions
# Using lists
rows = len(array_2d)
cols = len(array_2d[0]) if array_2d else 0
# Using NumPy
shape = np_array.shape # Returns (rows, cols)Transpose (Swap Rows and Columns)
# Using list comprehension
transposed = [[row[i] for row in array_2d] for i in range(len(array_2d[0]))]
# Using zip
transposed = [list(row) for row in zip(*array_2d)]
# Using NumPy
transposed = np_array.TFlatten to 1D Array
# Using list comprehension
flattened = [element for row in array_2d for element in row]
# Using sum()
flattened = sum(array_2d, [])
# Using NumPy
flattened = np_array.flatten()Sum All Elements
# Using nested loops
total = sum(sum(row) for row in array_2d)
# Using NumPy
total = np_array.sum()Practical Examples
Example 1: Matrix Addition
def add_matrices(matrix1, matrix2):
rows = len(matrix1)
cols = len(matrix1[0])
result = [[0 for _ in range(cols)] for _ in range(rows)]
for i in range(rows):
for j in range(cols):
result[i][j] = matrix1[i][j] + matrix2[i][j]
return result
# Usage
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
C = add_matrices(A, B) # [[6, 8], [10, 12]]
# With NumPy (much simpler)
C = np.array(A) + np.array(B)Example 2: Find Maximum Element
def find_max(array_2d):
max_val = array_2d[0][0]
max_pos = (0, 0)
for i, row in enumerate(array_2d):
for j, element in enumerate(row):
if element > max_val:
max_val = element
max_pos = (i, j)
return max_val, max_pos
# With NumPy
max_val = np_array.max()
max_pos = np.unravel_index(np_array.argmax(), np_array.shape)Example 3: Create Multiplication Table
def multiplication_table(n):
return [[(i+1) * (j+1) for j in range(n)] for i in range(n)]
table = multiplication_table(5)
# [[1, 2, 3, 4, 5],
# [2, 4, 6, 8, 10],
# [3, 6, 9, 12, 15],
# [4, 8, 12, 16, 20],
# [5, 10, 15, 20, 25]]Lists vs NumPy Arrays
| Feature | Nested Lists | NumPy Arrays |
|---|---|---|
| Import Required | No | Yes (import numpy) |
| Data Types | Mixed types allowed | Homogeneous (same type) |
| Performance | Slower for large data | Much faster |
| Memory | More memory | Less memory |
| Operations | Requires loops | Vectorized operations |
| Slicing | Limited | Advanced slicing |
| Best For | Small datasets, mixed types | Numerical computing, large data |
Common Pitfalls
Pitfall 1: Shallow Copy
# WRONG - creates shallow copies
array = [[0] * 3] * 3
array[0][0] = 1 # Changes ALL rows!
# CORRECT
array = [[0 for _ in range(3)] for _ in range(3)]
Pitfall 2: Index Out of Range
# Always check bounds
if i < len(array_2d) and j < len(array_2d[0]):
value = array_2d[i][j]Key Takeaways
Remember:
- 2D arrays in Python are implemented as nested lists or NumPy arrays
- Use list comprehension for initialization to avoid shallow copy issues
- Access elements with
array[row][col] - NumPy is much faster for numerical operations
- Use nested loops or list comprehension for iteration
- Always validate indices to avoid IndexError