multiple index inconsistency

Gonçalo Rodrigues op73418 at mail.telepac.pt
Wed Sep 18 23:24:16 CEST 2002


There is no bug here.

On Wed, 18 Sep 2002 13:59:58 -0700, bert <kilaruba at copper.net> wrote:

>The following line of code
>>>> a = 3*[range(3)]
>produces
>[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

What this does is create a list, named a, where each element references
*the same* list range(3) - That is the semantics of the * operator, it
only makes shallow copies.

>
>If I then write, say, 
>>>> a[0][1] = 3.7
>I get
>[[0, 3.7, 2], [0, 3.7, 2], [0, 3.7, 2]]
>and not
>[[0, 3.7, 2], [0, 1, 2], [0, 1, 2]]

So when you change one of them, since they are all aliases to the same
list, you in fact are changing all the elements.
>
>Now if I write
>>>> a = [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

Here no copies involved, since the list is built out of literals. They
are all different objects (different id's) - albeit equal.

>instead, and then 
>>>> a[0][1] = 3.7
>I get the result I expected (and wanted):
>[[0, 3.7, 2], [0, 1, 2], [0, 1, 2]]

So changing only one element changes... well, only one element.

>Why the inconsistency? Is this a bug or am I missing something?

There is no inconsistency. You just have to watch out that for mutable
objects (such as lists) this is the semantics - You will get the hang of
it.

All the best,
Gonçalo Rodrigues

P.S: BTW, I think there is a FAQ entry on this. You should read it.




More information about the Python-list mailing list