Two-dimensional arrays

Terry Reedy tjreedy at udel.edu
Tue May 27 02:38:25 EDT 2003


"monsterkodi" <monsterkodi at gmx.net> wrote in message
news:d9608a84.0305261648.797f8cec at posting.google.com...
> > A = [None]*3
> >  for i in range(3):
> >        A[i] = [None] * 2
>
> > w, h = 2, 3
> >  A = map(lambda i,w=w: [None] * w, range(h))
>
> > w,h = 2,3
> >  A = [ [None]*w for i in range(h) ]
>
> > dim1, dim2 = 3,5
> > multi = [ [ 0 for col in range(dim2)] for row in range(dim1) ]
>
> > array = [[0 for column in range(dim)] for row in range(dim)]
>
> > array = [[0]*dim for row in range(dim)]

Nice summary.  I think this and the equivalent above for None is best.

> > This is a known pitfall for Python beginners.  You are perhaps the
> > 10th person in the last several years to do and ask the same ;-)
>
> And I am sure: there are plenty more afraid to ask or trying to
comprehend the FAQ.
>
> Anybody else here who thinks that this is one of the very few
embarrasing sides of
> python?

What do you think anyone should be embarassed about?  In this respect,
Python acts entirely consistently with its object model and its
advertised syntax.

> Should this issue be worth another PEP?

What is the 'improvement' proposal?

> Am I missing some deeper knowledge which would enable me to see the
problem
> in providing 'low level' 'c-stylish' 'built-in' multidimensional
list features?

As I remember, C, unlike Fortran, does not have builtin
multidimensional arrays -- just arrays of arrays, much like Python.
So it is hard to know from the above what you think you are
suggesting.

If, in C, you do the equivalent to what you did and initialize an
array of pointer to array with the same pointer to the same array, so
that the inner array is 'aliased' multiple times, you will get the
same 'disconcerting' behaviour that changing the structure changes it,
regarless of how you subsequently look at it.  Any language that
allows aliasing -- multiple access paths to one mutable data
structure -- can have the same newcomer surprise.

Terry J. Reedy






More information about the Python-list mailing list