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 numpyBy universal convention, it's imported as np:
import numpy as npnp.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:
1a = np.array([[1, 2, 3],
2 [4, 5, 6Several functions create arrays filled with a starting value:
1np.zeros((2, 3), dtype=int) # 2x3 array of 0s
2np.ones(4) # Return: array([1., 1., 1., 1.]), floats by defaultChallenge 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:
1text = "123\n456\n789\n"
2digits = np.array([[int(ch) for ch in line] for line in textComparing a character array produces a boolean array, which the next sections make use of: walls = maze == "#".
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:
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].
.copy() when you need an independent array:1row = a[0]
2row[0] = 99 # a[0, 0] is now 99 as wellComparing 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:
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:
np.argwhere(a > 4) # Return: array([[1, 1], [1, 2]])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:
1a = np.array([[1, 2, 3],
2 [4, 5, 6When 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:
1a + np.array([10, 20, 30]) # Return: array([[11, 22, 33], [14, 25, 36]])
2a + np.array([[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:
1a.sum() # Return: np.int64(21)
2a.sum(axis=0) # Return: array([5, 7, 9]), column totals
3a.sumargmax 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:
1a.argmax() # Return: np.int64(5)
2np.unravel_index(a.argmax(), a.shape) # Return: (np.int64(1), np.int64(2))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:
1grid = np.array([[0, 1, 0],
2 [0, 1Each 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:
1grid = ((neighbors == 3) | ((grid == 1) & (neighbors == 2)))NumPy arrays double as matrices. .T transposes, and the @ operator is matrix multiplication; plain * multiplies element by element:
1m = np.array([[1, 2],
2 [3, 4]])
3Rotating and flipping a grid, which comes up constantly in puzzles about tiles and images, are single calls:
1np.rot90(m) # Return: array([[2, 4], [1, 3]]), 90 degrees counterclockwise
2np.rot90(m, k=-1) # 90 degrees clockwise
3The 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:
1coeffs = np.array([[2, 1],
2 [1, 3]])
3The 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.
NumPy isn't always the right tool. It shines on large, rectangular blocks of numbers of a single type. Plain lists are better when:
np.array([1, "a"]) silently converts everything to strings, and an array of general Python objects loses all the speed.1np.array([2**62]) * 4 # Return: array([0]), wrapped around
2Products 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.