I get an unexpected error when I try to print:

import numpy as np
a = np.array([11, 21, 31, 41, 51])
it = np.nditer(a, flags=['multi_index'], op_flags=['readwrite'])

while not it.finished:
    i = it.multi_index
    print("%d %d" % (i, a[i]))
    it.iternext()

This code generates the error:

TypeError: %d format: a number is required, not tuple

But when I simply do this:

for i in xrange(5):
    print("%d %d" % (i, a[i]))

Then I get the expected result:

0 11
1 21
2 31
3 41
4 51

So why do I get this error in the earlier case?

1  
Try print(repr((i, a[i]))) – Gribouillis 1 hour ago

4 Answers 4

i is not a number.

In [69]: it.multi_index
Out[69]: (0,)

Use i[0] instead.

You should try to use new style formatting

print("{} {}".format(i, a[i]))

If you really want the index and the element, you can use enumerate

for i, x in enumerate(np.nditer(a)):
    print("{} {}".format(i, x))

And, multi_index, as the name implies, is not an integer.

https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html

    
Thank you @cricket_007, very helpful! – waynemystir 1 hour ago

You're using it.multi_index that returns a tuple of indices.

As your array is 1D, replace i=it.multi_index with the index you wish to extract.

In your case, it should be i=it.multi_index[0]

i is of type tuple, use it.multi_index[0] to get the first element like below:

while not it.finished:
    i = it.multi_index[0]
    print("%d %d" % (i, a[i]))  # The better is using "{} {}".format(i, a[i])
    it.iternext()