Table of Contents
IronForgeCyber
Courses
Resources
Blog
Log In


IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. python
  3. numpy
8 min read

Arrays with NumPy

Python lists are flexible, but slow for numeric work: every element is a full Python object, and every operation on them runs through a Python loop. NumPy stores numbers in packed, typed arrays, the way C does, and applies operations to the whole array at once in compiled code. For grid puzzles, matrices, and anything that would otherwise be a nested loop over numbers, NumPy is both shorter to write and often a hundred times faster to run.

NumPy is a third-party package, so install it into your project first (see Packages & Environments):

$ uv add numpy

By universal convention, it's imported as np:

python
import numpy as np

Creating Arrays

np.array() builds an array from a list, or a list of lists for two dimensions. Every array has a shape, its size along each dimension as a tuple, and a dtype, the single type every element shares:

python
1a = np.array([[1, 2, 3],
2              [4, 5, 6

Several functions create arrays filled with a starting value:

python
1np.zeros((2, 3), dtype=int)    # 2x3 array of 0s
2np.ones(4)                     # Return: array([1., 1., 1., 1.]), floats by default

Reading a Grid

Challenge grids arrive as lines of text. A grid of digits becomes an integer array by converting each character, and a grid of symbols becomes an array of single-character strings:

python
1text = "123\n456\n789\n"
2digits = np.array([[int(ch) for ch in line] for line in text

Comparing a character array produces a boolean array, which the next sections make use of: walls = maze == "#".

Indexing and Slicing

A 2D array is indexed with one bracket and a comma, a[row, col], instead of a[row][col]. Each position can be a slice, so whole rows, columns and sub-grids come out in one step:

python
1a = np.array([[1, 2, 3],
2              [4, 5, 

Rows come first, so in a grid where x is horizontal, a cell is grid[y, x].

Slices are views
Slicing a NumPy array doesn't copy it. The slice is a view onto the same memory, so changing the slice changes the original array too. This is the opposite of slicing a Python list. Call .copy() when you need an independent array:
python
1row = a[0]
2row[0] = 99      # a[0, 0] is now 99 as well

Boolean Masks

Comparing an array with a value gives an array of True and False of the same shape, called a mask. Indexing with a mask selects the elements where it's True, and assigning through it changes only those elements:

python
1a = np.array([[1, 2, 3],
2              [4, 5,

Combine masks with & (and), | (or) and ~ (not), with each comparison in parentheses: a[(a > 1) & (a < 5)]. Python's and and or keywords don't work on arrays.

To get the positions where a condition holds, rather than the values, use np.argwhere, which returns one [row, col] pair per match:

python
np.argwhere(a > 4)    # Return: array([[1, 1], [1, 2]])

Vectorized Operations

Arithmetic on arrays happens element by element, with no loop in sight. This is called vectorization, and it's where NumPy's speed comes from:

python
1a = np.array([[1, 2, 3],
2              [4, 5, 6

When two arrays have different shapes, NumPy broadcasts them: a smaller array is stretched to match the larger one, as long as their shapes line up from the right. Adding a row adds it to every row; adding a column adds it to every column:

python
1a + np.array([10, 20, 30])       # Return: array([[11, 22, 33], [14, 25, 36]])
2a + np.array([[

Reductions

Functions like sum, min, max and mean reduce an array to a single value, or reduce along one axis when you pass axis. axis=0 collapses the rows, giving one result per column, and axis=1 collapses the columns, giving one result per row:

python
1a.sum()            # Return: np.int64(21)
2a.sum(axis=0)      # Return: array([5, 7, 9]), column totals
3a.sum

argmax and argmin return the position of the largest or smallest value. On a 2D array the position is counted as if the array were flattened, and np.unravel_index converts it back to a row and column:

python
1a.argmax()                                # Return: np.int64(5)
2np.unravel_index(a.argmax(), a.shape)     # Return: (np.int64(1), np.int64(2))

Counting Neighbors

Many grid puzzles, like cellular automata, need the number of neighbors around every cell. With loops, that's four nested levels. With NumPy, pad the grid with a border of zeros and add up eight shifted slices of it, one per direction:

python
1grid = np.array([[0, 1, 0],
2                 [0, 1

Each slice is the whole grid shifted one step in some direction, so adding them gives every cell's neighbor count at once. One more line applies the rules of Conway's Game of Life to every cell:

python
1grid = ((neighbors == 3) | ((grid == 1) & (neighbors == 2)))

Matrix Operations

NumPy arrays double as matrices. .T transposes, and the @ operator is matrix multiplication; plain * multiplies element by element:

python
1m = np.array([[1, 2],
2              [3, 4]])
3

Rotating and flipping a grid, which comes up constantly in puzzles about tiles and images, are single calls:

python
1np.rot90(m)            # Return: array([[2, 4], [1, 3]]), 90 degrees counterclockwise
2np.rot90(m, k=-1)      # 90 degrees clockwise
3

The np.linalg module solves linear algebra problems. A system of equations such as 2x + y = 5 and x + 3y = 10 is a matrix of coefficients and a vector of results, and np.linalg.solve finds x and y:

python
1coeffs = np.array([[2, 1],
2                   [1, 3]])
3

The answer comes back as floats, so round before converting when you expect whole numbers: np.rint(sol).astype(int). Floating-point error makes solve unreliable for exact answers with very large numbers; for those, Python integers or a library like SymPy are the safer choice.

When to Stay with Lists

NumPy isn't always the right tool. It shines on large, rectangular blocks of numbers of a single type. Plain lists are better when:

  • Rows have different lengths. NumPy arrays must be rectangular.
  • Items have mixed types. np.array([1, "a"]) silently converts everything to strings, and an array of general Python objects loses all the speed.
  • The data grows one item at a time. Appending to an array copies the whole thing every time; build a list, then convert it once at the end.
  • Numbers might get huge. This one matters most in challenges.
NumPy integers overflow
NumPy integers are fixed-width, usually 64 bits, like C's. Unlike Python's integers, which never overflow, they wrap around silently when a result is too large, with no error:
python
1np.array([2**62]) * 4                  # Return: array([0]), wrapped around
2
]
]
)
3a.shape # Return: (2, 3), 2 rows and 3 columns
4a.dtype # Return: dtype('int64')
5a.ndim # Return: 2
3np.full((2, 2), 7) # 2x2 array of 7s
4np.arange(0, 10, 3) # Return: array([0, 3, 6, 9]), like range()
.
splitlines
(
)
]
)
3
4maze = np.array([list(line) for line in "#.#\n...\n#.#".splitlines()])
5maze.shape # Return: (3, 3)
6
]
]
)
3a[1, 2] # Return: 6
4a[0] # Return: array([1, 2, 3]), the first row
5a[:, 1] # Return: array([2, 5]), the second column
6a[:, ::-1] # every row reversed
3row = a[0].copy()
6
]
]
)
3a > 2 # Return: array([[False, False, True], [ True, True, True]])
4a[a > 2] # Return: array([3, 4, 5, 6])
5(a > 2).sum() # Return: np.int64(4), counting the True values
6a[a % 2 == 0] = 0 # zero out every even number in place
]
]
)
3a * 10 # Return: array([[10, 20, 30], [40, 50, 60]])
4a + a # Return: array([[ 2, 4, 6], [ 8, 10, 12]])
5a ** 2 # every element squared
100
]
,
[
200
]
]
)
# Return: array([[101, 102, 103], [204, 205, 206]])
(
axis
=
1
)
# Return: array([ 6, 15]), row totals
4a.max(axis=1) # Return: array([3, 6])
,
0
]
,
3 [0, 1, 0]])
4
5p = np.pad(grid, 1) # a border of zeros around the grid
6neighbors = sum(
7 p[1 + dy : 1 + dy + grid.shape[0], 1 + dx : 1 + dx + grid.shape[1]]
8 for dy in (-1, 0, 1)
9 for dx in (-1, 0, 1)
10 if (dy, dx) != (0, 0)
11)
12
13neighbors
14# Return: array([[2, 1, 2],
15# [3, 2, 3],
16# [2, 1, 2]])
.
astype
(
int
)
2# grid = [[0, 0, 0], [1, 1, 1], [0, 0, 0]], the vertical bar flips horizontal
m
.
T
# Return: array([[1, 3], [2, 4]])
4m @ m # Return: array([[ 7, 10], [15, 22]])
5m * m # Return: array([[ 1, 4], [ 9, 16]])
np
.
flip
(
m
,
axis
=
1
)
# Return: array([[2, 1], [4, 3]]), mirrored left to right
results
=
np
.
array
(
[
5
,
10
]
)
4np.linalg.solve(coeffs, results) # Return: array([1., 3.]), so x = 1 and y = 3
2
**
62
*
4
# Return: 18446744073709551616

Products and sums in puzzle answers can easily pass 2⁶³. When the numbers might get that big, convert to Python integers before the arithmetic: int(a.prod()) is too late, since the overflow already happened inside NumPy, but math.prod(a.tolist()) multiplies Python integers and gets the right answer.