I'm trying to cycle through the elements of an array aa
, where the for
block is not applied over it but over another array bb
.
import numpy as np
from itertools import cycle
aa = np.array([[399., 5., 9.], [9., 35., 2.], [.6, 15., 8842.]])
c_aa = cycle(aa)
bb = np.array([33, 1., 12, 644, 234, 77, 194, 70])
for _ in bb:
print(c_aa)
This does not work, it simply outputs:
<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>
<itertools.cycle object at 0x7f8d207b1640>
But if I change that last line for print(list(c_aa))
my entire system almost hangs.
What is going on here and how can I iterate over aa
without using it in the for
call?
Since the cycle goes infinitely, calling list()
on it is a bad idea, as you've discovered. You can call next()
on the iterator to get the next value, however:
import numpy as np
from itertools import cycle
aa = np.array([[399., 5., 9.], [9., 35., 2.], [.6, 15., 8842.]])
c_aa = cycle(aa)
bb = np.array([33, 1., 12, 644, 234, 77, 194, 70])
for _ in bb:
print(next(c_aa))