[Numpy-discussion] array allocation using tuples gives views of same array

Timothy Hochberg tim.hochberg@ieee....
Thu Nov 15 10:32:24 CST 2007


On Nov 15, 2007 9:11 AM, Hans Meine <meine@informatik.uni-hamburg.de> wrote:

> Am Donnerstag, 15. November 2007 16:29:12 schrieb Warren Focke:
> > On Thu, 15 Nov 2007, George Nurser wrote:
> > > It looks to me like
> > > a,b = (zeros((2,)),)*2
> > > is equivalent to
> > > x= zeros((2,))
> > > a,b=(x,)*2
> >
> > Correct.
> >
> > > If this is indeed a feature rather than a bug, is there an alternative
> > > compact way to allocate many arrays?
> >
> > a, b = [zeros((2,)) for x in range(2)]
>
> Let me add that this is a standard Python caveat, which also happens with
> lists -- many of us have once tried to initialize an array of empty lists
> with ([], ) * N, which results in N references to the same empty list.
> Warren pointed out the standard solution above.


And I'll just add that another option in this case is to avoid tuples and
lists altogether and just unpack a larger array:

a, b = zeros([2,2])

That's mostly inferior to the list comprehension solution in terms of
clarity, but may appeal to the fans of the pithy. In some cases it also
expresses intent better, but not often.


<OFF TOPIC EDITORIAL>

Using lists for shapes is clearer both typographically: compare zeros((2,))
and zeros([2]), and conceptually: shapes are closer to lists (variable
length, homogeneous) than tuples (fixed length, inhomogeneous).  Tuples are
used for the shape attribute since they need to be immutable, but there's no
reason to type them that way; it just makes things hard to read.

<OFF TOPIC EDITORIAL>


-- 
.  __
.   |-\
.
.  tim.hochberg@ieee.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20071115/7696e603/attachment.html 


More information about the Numpy-discussion mailing list