[Tutor] python 2D list

Alan Gauld alan.gauld at btinternet.com
Sat May 24 01:50:30 CEST 2008


"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

This creates a list with 3 zeros then creates a second list
with 4 references to the first list.

Remember that in Python all variables are references.

> >>> 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

Because your list is 4 references to the same list.
You changed the underlying list so all references
reflect the change.

> This is a little confusing and inconsistent with almost all other 
> languages.  Could anyone please help

Its not inconsistent with, say C/C++ if you think of a
C array of pointers. Something like (My C is rusty!)

void main()
{
   int *ia = {0,0,0};
   int **ipa = {ia,ia,ia};

   ipa[1][2] = 1;
}

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld






More information about the Tutor mailing list