Create multi-dimensional arrays in pure Python: The Correct Way
The 30-minute bug
Yesterday I burned half an hour chasing a bug because I got lazy and wrote this to spin up a 5×5 matrix in pure Python:
n = 5
array = [[0] * n] * n
Look how clean that is. One line. Zero imports.
Then I tried flipping a single cell, and the entire column flipped with it like a cursed game of Minesweeper:
array[0][0] = 1
print(array)
# [[1, 0, 0, 0, 0],
# [1, 0, 0, 0, 0],
# [1, 0, 0, 0, 0],
# [1, 0, 0, 0, 0],
# [1, 0, 0, 0, 0]]
Once you see it in isolation, it’s obvious. Buried inside a bigger program — when your brain is used to having numpy around and completely forgets how pure Python lists behave — it is deeply humbling.
Here is what actually happened, stripped down to a tiny object:
from dataclasses import dataclass
@dataclass
class Num:
val: int
zero = Num(0)
array = [zero] * 5
print(array)
# [Num(val=0), Num(val=0), Num(val=0), Num(val=0), Num(val=0)]
Looks like five Num objects. It isn’t. It’s one Num object wearing five trench coats:
array[0] is array[1]
# True
Poke one of them, and all five flinch:
array[0].val = 1
print(array)
# [Num(val=1), Num(val=1), Num(val=1), Num(val=1), Num(val=1)]
My 5×5 matrix had the exact same problem. I didn’t make five rows of zeroes — I made one row of zeroes and stuck five references to it into a list. So array[0] and array[1] are literally the same list.
Wait — then why didn’t [0] * n blow up?
Fair question. If * just repeats the same object over and over, [0] * 5 puts the exact same 0 in every slot. Yet changing one slot doesn’t corrupt the whole row:
row = [0] * 5
row[0] is row[1] # True — yep, literally the same 0
row[0] = 1
print(row)
# [1, 0, 0, 0, 0] — totally fine
The trick is that assigning to a list slot (row[0] = 1) never modifies the 0. It just points slot 0 at a different object (1) and leaves the other four slots pointing at 0. It isn’t even special to integers — the same thing happens with Num:
array = [Num(0)] * 5
array[0] = Num(1) # re-point slot 0 to a brand new object
print(array)
# [Num(val=1), Num(val=0), Num(val=0), Num(val=0), Num(val=0)]
array[1].val = 2 # mutate the shared object in place
print(array)
# [Num(val=1), Num(val=2), Num(val=2), Num(val=2), Num(val=2)]
Sharing an object is harmless until you mutate it in place. Because integers are immutable, you literally can’t mutate a 0 in place, so [0] * 5 is completely safe. Lists, on the other hand, are very mutable, and very happy to ruin your afternoon.
The boring (correct) fix
Use a list comprehension so Python actually builds a fresh object on every iteration:
array = [Num(val=0) for _ in range(5)]
array[0] == array[1] # True — same value
array[0] is array[1] # False — five actual objects
For a 2D matrix:
array = [[0] * num_cols for _ in range(num_rows)]
Keep the * on the inside — those zeroes are immutable, so it’s both safe and fast. You could write a double list comprehension ([[0 for _ in range(num_cols)] for _ in range(num_rows)]), but it’s noisier and, when I timed it on a 1000×1000 grid, several times slower because the inner loop runs in Python instead of C.
Bonus trap:
copy.deepcopywill not rescue you here. It’s too faithful — it preserves shared references, socopy.deepcopy([[0] * 3] * 2)gives you a brand new outer list containing… the exact same brand new row, twice.
Same bug, different trench coats
Once this clicks, you start spotting the exact same footgun all over Python. It’s always one mutable object accidentally shared across multiple places:
# 1. dict.fromkeys with a mutable default
d = dict.fromkeys(["a", "b", "c"], [])
d["a"].append(1)
print(d)
# {'a': [1], 'b': [1], 'c': [1]}
# 2. The infamous mutable default argument
def add_gig(gig, gigs=[]):
gigs.append(gig)
return gigs
add_gig("Monday") # ['Monday']
add_gig("Tuesday") # ['Monday', 'Tuesday'] — surprise!
# 3. A mutable class attribute
class Dog:
tricks = []
a, b = Dog(), Dog()
a.tricks.append("sit")
print(b.tricks)
# ['sit'] — b learned it via telepathy
Number 2 is probably Python’s single most famous gotcha: default arguments are evaluated once when the def runs, not each time you call the function. Same bug, different costume.
The wrong (and much more fun) fix
After fixing my actual code, I couldn’t resist opening CPython’s list_repeat to see what * actually does in C:
static PyObject *
list_repeat(PyListObject *a, Py_ssize_t n)
{
Py_ssize_t i, j;
Py_ssize_t size;
PyListObject *np;
PyObject **p, **items;
PyObject *elem;
if (n < 0)
n = 0;
if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
return PyErr_NoMemory();
size = Py_SIZE(a) * n;
if (size == 0)
return PyList_New(0);
np = (PyListObject *) list_new_prealloc(size);
if (np == NULL)
return NULL;
if (Py_SIZE(a) == 1) {
items = np->ob_item;
elem = a->ob_item[0];
for (i = 0; i < n; i++) {
items[i] = elem;
Py_INCREF(elem);
}
}
else {
p = np->ob_item;
items = a->ob_item;
for (i = 0; i < n; i++) {
for (j = 0; j < Py_SIZE(a); j++) {
*p = items[j];
Py_INCREF(*p);
p++;
}
}
}
Py_SET_SIZE(np, size);
return (PyObject *) np;
}
My C is rusty, so here’s the two-sentence translation:
ais a pointer to thePyListObject.a->ob_itemis an array of pointers to the actualPyObjectelements inside the list (defined here).
All list_repeat does is allocate a new list np, copy the pointers from a->ob_item into np->ob_item n times, and bump their reference counts (Py_INCREF). If Num(0) lives at 0xABC, [Num(0)] * 5 is just [0xABC, 0xABC, 0xABC, 0xABC, 0xABC].
History nugget: Guido’s original commit implementing
list_repeatis still sitting in git history from 1991.
Naturally, I wondered: what if I just “fix” Python myself with memcpy? So I forked CPython locally, rolled up my sleeves, and wrote this crime against computer science:
static PyObject *
list_repeat(PyListObject *a, Py_ssize_t n)
{
Py_ssize_t i, j;
Py_ssize_t size;
PyListObject *np;
PyObject **p, **items;
PyObject *elem;
PyTypeObject *elem_type;
Py_ssize_t elem_size;
if (n < 0)
n = 0;
if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
return PyErr_NoMemory();
size = Py_SIZE(a) * n;
if (size == 0)
return PyList_New(0);
np = (PyListObject *) list_new_prealloc(size);
if (np == NULL)
return NULL;
if (Py_SIZE(a) == 1) {
items = np->ob_item;
elem = a->ob_item[0];
elem_type = Py_TYPE(elem);
elem_size = elem_type->tp_basicsize + abs(Py_SIZE(elem)) * elem_type->tp_itemsize;
for (i = 0; i < n; i++) {
PyObject *s = (PyObject *)PyObject_Malloc(elem_size);
memcpy(s, elem, elem_size);
items[i] = s;
Py_INCREF(s);
Py_INCREF(elem);
}
}
else {
p = np->ob_item;
items = a->ob_item;
for (i = 0; i < n; i++) {
for (j = 0; j < Py_SIZE(a); j++) {
elem = items[j];
elem_type = Py_TYPE(elem);
elem_size = elem_type->tp_basicsize + abs(Py_SIZE(elem)) * elem_type->tp_itemsize;
PyObject *s = (PyObject *)PyObject_Malloc(elem_size);
memcpy(s, elem, elem_size);
*p = s;
Py_INCREF(*p);
p++;
}
}
}
Py_SET_SIZE(np, size);
return (PyObject *) np;
}
I recompiled Python, ran my Num test, and felt like a genius for about three seconds:
zero = Num(0)
array = [zero] * 5
array[0] is array[1]
# False — brand new pointers! Victory!
array[0].val = 1
array[1].val
# 1 — wait, what?!
Two completely different objects, and they were still sharing state.
Why? Because a Num instance doesn’t actually store val directly inside its struct — it stores a pointer to its __dict__, and val lives in there. Blindly calling memcpy on the Num struct just copied that __dict__ pointer, creating two distinct Python objects sharing the exact same bag of attributes. You don’t even need to recompile CPython to reproduce this cursed twin trick:
zero = Num(0)
twin = Num.__new__(Num) # a fresh, empty Num...
twin.__dict__ = zero.__dict__ # ...sharing zero's insides
twin is zero # False — two different objects
zero.val = 1
twin.val # 1 — still joined at the hip
And honestly, the shared __dict__ was the least of my sins. My memcpy also cloned the original object’s reference count, never told __dict__ it had a second owner (so freeing the original frees __dict__ right out from under the copy), and bypassed every bit of GC tracking CPython expects. I didn’t implement deep copy — I implemented a segfault with extra steps. It’s a minor miracle the interpreter stayed alive long enough to print 1.
To actually make * deep-copy elements safely, CPython would have to run arbitrary Python code on every multiplication — turning [0] * 1_000_000 into a crawl for everyone just to save me 30 minutes of debugging.
Guido made the right call in 1991. I’ll stick to list comprehensions.