Yet another "simple" headscratcher

Gary Herron gary.herron at islandtraining.com
Fri May 30 23:57:32 EDT 2014


On 05/30/2014 08:38 PM, Josh English wrote:
> ...
>
> def zero_matrix(rows, cols):
>      row = [0] * cols
>      data = []
>      for r in range(rows):
>          data.append(row)
>
>      return Matrix(data)

There is a simple and common newbie mistake here.    It looks like you 
are appending several copies of a zero row to data, but in fact you are 
appending multiple references to a single row.  (The hint is that you 
only created *one* row.)

Put the
    row = [0] * cols
inside the loop so each append is using its own row rather than one 
shared row being used multiple times.


Here's a small example that demonstrates problem:

 >>> row = [0,0,0,0]
 >>> data = []
 >>> data.append(row)
 >>> data.append(row)
 >>> data[0][0] = 99
 >>> data
[[99, 0, 0, 0], [99, 0, 0, 0]]


Gary Herron






More information about the Python-list mailing list