[Numpy-discussion] array allocation using tuples gives views of same array
George Nurser
gnurser at googlemail.com
Thu Nov 15 12:31:43 EST 2007
On 15/11/2007, Timothy Hochberg <tim.hochberg at ieee.org> wrote:
>
>
> On Nov 15, 2007 9:11 AM, Hans Meine <meine at 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])
Pithy indeed. I didn't realize that one could unpack numpy arrays.
> <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>
Makes sense.
Thanks to everybody for their help. George.
More information about the NumPy-Discussion
mailing list