numpy array equivalent for += operator
numpy, python
Solution
Use `np.fromiter`:
def f(n):
for j in range(n):
yield j
>>> np.fromiter(f(5), dtype=np.intp)
array([0, 1, 2, 3, 4])
If you know beforehand the number of items the iterator is going to return, you can speed things up using the `count` keyword argument:
>>> np.fromiter(f(5), dtype=np.intp, count=5)
array([0, 1, 2, 3, 4])
Problem
I often do the following: ``` import numpy as np def my_generator_fun(): yield x # some magically generated x A = [] for x in my_generator_fun(): A += [x] A = np.array(A) ``` Is there a better solution to this which operates on a numpy array from the start and avoids the creation of a standard python list? Note that the += operator allows to extend an empty and dimensionless array with an arbitrarily dimensioned array whereas np.append and np.concatenate demand for equally dimensioned arrays.