Why does r_[r_] hang?

Viewed 81

This must be one of the shortest numpy hangs possible. Please don't ask why on earth I even tried this.

from numpy import r_
r_[r_]

Try it online!

Is this the correct behaviour (and if so: why?) or a bug?

1 Answers

That is an interesting oddity you've found! It gets stuck for the same reason that list(r_) hangs, it's essentially in an infinite loop trying to iterate an infinite iterable.

Since an object which implements __getitem__ is considered iterable, r_ is iterable, yielding r_[0], r_[1], r[2]... etc

>>> import numpy as np
>>> it = iter(np.r_)
>>> next(it)
array([0])
>>> next(it)
array([1])
>>> next(it)
array([2])
>>> next(it)
array([3])
...

Note that r_[obj] iterates obj (source) so r_[r_] will iterate itself indefinitely.

Related