3

I envision something like

import numpy as np
x = np.arange(10)
for i, j in x:
     print(i,j)

and get something like

0 1
2 3
4 5
6 7
8 9

But I get this traceback:

Traceback (most recent call last):
  File "/home/andreas/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/223.8214.51/plugins/python/helpers/pydev/pydevconsole.py", line 364, in runcode
    coro = func()
  File "<input>", line 1, in <module>
TypeError: cannot unpack non-iterable numpy.int64 object

I also tried to use np.nditer(x) and itertools with zip(x[::2], x[1::2]), but that does not work either, with different error messages.

This should be super simple, but I can't find solutions online.

1
  • 2
    What is the purpose of the iteration? There is likely a more efficient (numpy-esque) approach. Commented Jan 14, 2023 at 13:02

3 Answers 3

4

You were trying to put 0 into i and j which is not possible. To achieve that result you'll have to reshape your numpy array using either x = x.reshape((5,2)) or x.shape = 5, 2. Then you can unpack it like that.

To visualize, this is what your current code is doing:

i, j = 0
...
i, j = 1
...

And this is what will happen if you reshape it:

i, j = [0, 1]
...
i, j = [2, 3]
...

Edit:

import numpy as np
N = 10

x = np.arange(N).reshape((N/2, 2))
for i, j in x:
     print(i,j)
Sign up to request clarification or add additional context in comments.

4 Comments

oh, i understand, thank you for explaining it in simple terms!
your solution is best so far. if you would please provide a snippet, so i can accept your answer. @wingedseal
I'm on mobile and won't be able to access my laptop for quite a while
I coded my solution based on your suggestion and am in no hurry. Just do it later.
0

Trying to be faithful to the original attempt. zipping tuples of pairs of even and odds:

import numpy as np
x = np.arange(10)

for i, j in zip(x[::2], x[1::2]):
     print(i,j)

2 Comments

Does that run for you? I tried that (as mentioned) and got an error.
yes, running numpy 1.23, test it also here
0

Is it what you want?

for x in range(0,10,2):
    print(x, x+1)

or your values are maintained in the numpy array x, then

for i in range(0, len(x), 2):
    print(x[i],x[i+1])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.