0

Im trying to understand the following code:

A = np.arange(3).reshape(3,1)
B = np.arange(3).reshape(1,3)
it = np.nditer([A,B,None])
for x,y,z in it: z[...] = x + y
print(it.operands[2])

And I can't figure out what [...] is doing.

EB97
  • 69
  • 2
  • 6
  • Also Related: [What does “three dots” in Python mean when indexing what looks like a number?](https://stackoverflow.com/q/42190783/15497888) and [What is the difference between the `slice` (:) and the `ellipsis` (…) operators in `numpy`?](https://stackoverflow.com/q/63314098/15497888) – Henry Ecker May 09 '21 at 12:44
  • Note that the code as shown is just a complicated way to compute `A + B`. Not really sure why it would be written that way, unless there is some additional context missing. – chepner May 09 '21 at 13:28
  • And https://stackoverflow.com/questions/772124/what-does-the-ellipsis-object-do – DavidW May 09 '21 at 14:27
  • It is used here because `z` is a 0d array, created by `nditer`. A numpy beginner shouldn't be studying `nditer`. It's complex and doesn't do anything for performance. – hpaulj May 09 '21 at 15:04
  • thank you all for the answers. @hpaulj haha maybe you're right but i still need to know this. i understand that 'nditer' just helps you iterate over arays, so if it's more complex than that i would like you to enlighten me please. – EB97 May 09 '21 at 16:48
  • We try not to iterate over arrays. `A+B` does this kind of iteration, but in fast compiled code. Where's this code sample from? – hpaulj May 09 '21 at 16:59
  • @NelsonGon thanks for answering, but unfortunately no. in what you sent it explains that [...] means an infinit nested list and i can't see it in my example. – EB97 May 09 '21 at 17:02
  • @hpaulj https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises_with_hints_with_solutions.md – EB97 May 09 '21 at 19:47
  • That's a so-so list of examples. This example does what the name suggests, but I wouldn't invest too much time in trying to understand it. '...' stands for any number of ':' slices, even 0. Try: `aa=np.array(3); aa[...]=4; aa` – hpaulj May 09 '21 at 20:44

1 Answers1

0

z is an element of your output. The most common usecase to modify it is via this statement z[...] = # something. The ... is an ellipsis.
What your code does is basically iterate over A and B in a nested forloop, and write the output to the third element of the nditer object.Much like the below code.

To read more about ellipsis, see https://docs.python.org/dev/library/constants.html#Ellipsis

To read more about python iter output, see https://numpy.org/doc/stable/reference/arrays.nditer.html
Especially Iterator-Allocated Output Arrays section

Gábor Pálovics
  • 455
  • 4
  • 12
  • `nditer` docs have two major problems. It claims to be "efficient", and it omits crucial details, such as the nature of the iteration variables. Too many beginners are mislead. – hpaulj May 09 '21 at 16:02