Is there any reason to introduce this intermediate variable (sz)?

Terry Reedy tjreedy at udel.edu
Wed Nov 18 05:02:13 EST 2015


On 11/17/2015 3:51 PM, fl wrote:

> n_iter = 50
> sz = (n_iter,) # size of array
> x = -0.37727
> z = np.random.normal(x,0.1,size=sz)
>
> Q = 1e-5 # process variance
>
> # allocate space for arrays
> xhat=np.zeros(sz)
> P=np.zeros(sz)
>
>
> I learn Python now and the above code seems from an experienced author.
> The curious thing to me is the variable 'sz'.

'sz' is a name and in the program above, it is a constant tuple derived 
from constant int n_iter.  Since the tuple is used more than once, 
calculating it just once and naming it is a good idea.

 > I have check np.zeros(shape, ..)

Reading about the the signature of functions that you use or read about 
is a good idea and quite normal.

> shape : int or sequence of ints

> The introduced 'sz' is a tuple.

and tuples are sequences.

 > If n_iter function is similar to a constant in C,

n_iter is a named constant, not a function, as you note below.

 > I don't see the reason for 'sz'.

I gave a reason for it existig above, but I think you are asking about 
its use in the particular location.

> In fact, 'n_iter' is an int, which fits  the below
>
> np.zeros(shape)
>
> correctly.  Could you see something useful with variable 'sz'?

I would presume until I tried it that np.zeros(50) and np.zeros((50,)) 
are different (have a different shape).  If they are not, then the use 
of a singleton tuple is confusing, whether or not the tuple is given a name.

-- 
Terry Jan Reedy




More information about the Python-list mailing list