Yet another "simple" headscratcher

Ian Kelly ian.g.kelly at gmail.com
Fri May 30 23:54:00 EDT 2014


On Fri, May 30, 2014 at 9:38 PM, Josh English
<Joshua.R.English at gmail.com> wrote:
> I am trying to whip up a quick matrix class that can handle multiplication.
>
> Should be no problem, except when it fails.
>
> [SNIP]
>
> def zero_matrix(rows, cols):
>     row = [0] * cols
>     data = []
>     for r in range(rows):
>         data.append(row)

Each row of the matrix that you create here is the *same* list, not
different lists that happen to be equal.  So when you mutate one row,
you mutate all of them.  See:
https://docs.python.org/3/faq/programming.html#how-do-i-create-a-multidimensional-list



More information about the Python-list mailing list