Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does r_[r_] hang?

Tags:

python

numpy

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?

like image 686
Albert.Lang Avatar asked Aug 30 '25 18:08

Albert.Lang


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.

like image 96
wim Avatar answered Sep 02 '25 08:09

wim