# [Numpy-discussion] ndrange, like range but multidimensiontal

Stephan Hoyer shoyer at gmail.com
Wed Oct 10 12:07:50 EDT 2018

```On Tue, Oct 9, 2018 at 9:34 PM Eric Wieser <wieser.eric+numpy at gmail.com>
wrote:

> One thing that worries me here - in python, range(...) in essence
> generates a lazy list - so I’d expect ndrange to generate a lazy ndarray.
> In practice, that means it would be a duck-type defining an __array__
> method to evaluate it, and only implement methods already present in numpy.
>
> It’s not clear to me what the datatype of such an array-like would be.
> Candidates I can think of are:
>
>    1. [('i0', intp), ('i1', intp), ...], but this makes tuple coercion a
>    little awkward
>
> I think this would be the appropriate choice. What about it makes tuple
coercion awkward? If you use this as the dtype, you both set and get
element as tuples.

In particular, I would say that ndrange() should be a lazy equivalent to
the following explicit constructor:

def ndrange(shape):
dtype = [('i' + str(i), np.intp) for i in range(len(shape))]
array = np.empty(shape, dtype)
for indices in np.ndindex(*shape):
array[indices] = indices
return array

>>> ndrange((2,)
array([(0,), (1,)], dtype=[('i0', '<i8')])

>>> ndrange((2, 3))
array([[(0, 0), (0, 1), (0, 2)], [(1, 0), (1, 1), (1, 2)]], dtype=[('i0',
'<i8'), ('i1', '<i8')])

The one deviation in behavior would be that ndrange() iterates over
flattened elements rather than the first axes.

It is indeed a little awkward to have field names, but given that NumPy
creates those automatically when you supply a dtype like 'i8,i8' this is
probably a reasonable choice.

>    1. (intp, (N,)) - which collapses into a shape + (3,) array
>    2. object_.
>    3. Some new np.tuple_ dtype, a heterogenous tuple, which is like the
>    structured np.void but without field names. I’m not sure how
>    vectorized element indexing would be spelt though.
>
> Eric
> ​
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20181010/1b80c63d/attachment.html>
```