[Tutor] Fwd: python 2D list

W W srilyk at gmail.com
Sat May 24 01:33:22 CEST 2008


Oops! Forgot to "Reply to All"

----------------

I'm not sure but take a look at this:

>>> a = [[0]*3]*4
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[1]
[0, 0, 0]
>>> a[0][0] = 4
>>> a
[[4, 0, 0], [4, 0, 0], [4, 0, 0], [4, 0, 0]]
>>> b = [[0,0,0],[0,0,0],[0,0,0]]
>>> b
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> b[0][0] = 4
>>> b
[[4, 0, 0], [0, 0, 0], [0, 0, 0]]

I think, if I'm not mistaken, that one part of your initialisation
only creates 3 aliases, similar to something like this:

list = [0, 0, 0]
list = [list, list, list]

and further testing supports this hypothesis:

>>> list = [4400, 60, 70]
>>> list = [list, list, list]
>>> list
[[4400, 60, 70], [4400, 60, 70], [4400, 60, 70]]
>>> list[0][1] = 'foo'
>>> list
[[4400, 'foo', 70], [4400, 'foo', 70], [4400, 'foo', 70]]


HTH,
Wayne

On Fri, May 23, 2008 at 4:22 PM, Yuanxin Xi <yxi at bcm.edu> wrote:
> I'm a Python newbie and still exploring, just surprised to see this 2D list
> assignment while debugging.
>
>>>> a = [[0] *3] *4
>>>> a
> [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>>> a[1][2] = 1
>>>> a
> [[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]]
>
> why is that a[0][2] a[1][2] a[2][2] a[3][2] are all assigned to 1 instead of
> only a[1][2] = 1?  This is a little confusing and inconsistent with almost
> all other languages.  Could anyone please help explain the assignment
> mechanism here?  Thanks
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



--
To be considered stupid and to be told so is more painful than being
called gluttonous, mendacious, violent, lascivious, lazy, cowardly:
every weakness, every vice, has found its defenders, its rhetoric, its
ennoblement and exaltation, but stupidity hasn't. - Primo Levi



-- 
To be considered stupid and to be told so is more painful than being
called gluttonous, mendacious, violent, lascivious, lazy, cowardly:
every weakness, every vice, has found its defenders, its rhetoric, its
ennoblement and exaltation, but stupidity hasn't. - Primo Levi


More information about the Tutor mailing list