DEV Community

Serguey Asael Shinder
Serguey Asael Shinder

Posted on

You Built the Shelf Grid With One Multiplication and Every Aisle Changed Together

The warehouse screen
showed three aisles,
four shelves each,
and how many pallets sat on every shelf.

The grid started empty:

grid = [[0] * 4] * 3

Short.

Readable.

It printed exactly right:

[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]

Then a forklift driver
put five pallets
on aisle one, shelf two.

grid[0][1] = 5

And the screen said
aisle two had five pallets there too.

So did aisle three.

Nobody had touched them.

Here is the mechanism.

The inner part, [0] * 4,
builds one list
with four zeros in it.

Fine.

Numbers cannot be changed in place,
so sharing them costs nothing.

The outer part, * 3,
does not build three lists.

It builds one outer list
holding three references
to the same inner list.

Three names on one shelf.

When you wrote to "aisle one",
you wrote to the only row there was,
and every aisle
was looking at it.

The print could not warn you.

Three references to one list
look exactly like
three lists that happen to be equal.

The fix is to make the inner list
once per row:

grid = [[0] * 4 for _ in range(3)]

The comprehension runs its expression
three times,
so you get three separate lists.

Once you see it,
you find it everywhere.

[[]] * 3
is one empty list, three times.

dict.fromkeys(branches, [])
gives every branch
the same list of orders.

In JavaScript,
new Array(3).fill([])
fills three slots
with one array.

Array.from({ length: 3 }, () => [])
makes three.

Same shape of bug,
different language.

The rule underneath is short.

Copying a container
copies the references,
not what they point to.

Repeat a number
and you get numbers.

Repeat a list
and you get one list
with several ways in.

So when a write
turns up in places you never wrote,
stop asking what changed the data.

Ask how many objects
there really are.

– Serguey Asael Shinder

Top comments (0)