Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #72327
| Date | 2014-05-30 20:57 -0700 |
|---|---|
| From | Gary Herron <gary.herron@islandtraining.com> |
| Subject | Re: Yet another "simple" headscratcher |
| References | <a7dbde77-6bec-4b04-a940-5e8beb926232@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.10503.1401508915.18130.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Yet another "simple" headscratcher Josh English <Joshua.R.English@gmail.com> - 2014-05-30 20:38 -0700
Re: Yet another "simple" headscratcher Josh English <Joshua.R.English@gmail.com> - 2014-05-30 20:55 -0700
Re: Yet another "simple" headscratcher Gary Herron <gary.herron@islandtraining.com> - 2014-05-30 20:57 -0700
Re: Yet another "simple" headscratcher Ian Kelly <ian.g.kelly@gmail.com> - 2014-05-30 21:54 -0600
Re: Yet another "simple" headscratcher wxjmfauth@gmail.com - 2014-05-30 23:46 -0700
csiph-web