While you can create a 1D array from a generator with
numpy.fromiter(), you can create an N-D array from a generator with
>>> mygen = (np.ones((5, 3)) for _ in range(10)) >>> x = numpy.stack(mygen) >>> x.shape (10, 5, 3)
It also works for 1D arrays:
>>> numpy.stack(2*i for i in range(10)) array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
numpy.stack is internally consuming the generator and creating an intermediate list with
arrays = [asanyarray(arr) for arr in arrays]. The implementation can be found here.
[WARNING] As pointed out by @Joseh Seedy, Numpy 1.16 raises a warning that defeats usage of such function with generators.