np.broadcast
returns an instance of an iterator object that describes how arrays should be translated together. 1 Among other things, it describes the shape and number of dimensions that the resulting array will have,
Actually, when you actually iterate over this object in Python, you return tuples of elements from each input array:
>>> b = np.broadcast(x, x) >>> b.shape (3,) >>> b.ndim 1 >>> list(b) [(1, 1), (2, 2), (3, 3)]
This tells us that if we were to perform the actual operation on arrays (for example, x+x
), NumPy would return an array of the form (3,)
, one dimension and combine the elements in the tuple to create values โโin the final array (for example, it would perform 1+1
, 2+2
, 3+3
to add).
If you delve into the vstack source, you will find that everything it does is make sure that the elements of iterability are at least two-dimensional, and then stack them along the 0 axis.
In the case of b = np.broadcast(x, x)
this means that we collect the following arrays:
>>> [np.atleast_2d(_m) for _m in b] [array([[1, 1]]), array([[2, 2]]), array([[3, 3]])]
These three small arrays are then stacked vertically, producing the output you mark.
1 Exactly how arrays of different dimensions are repeated in parallel lies at the heart of how NumPy broadcasting works. The code can be found mainly in iterators.c . An interesting review of the multidimensional NumPy iterator, written by Travis Oliphant himself, can be found in the book Beautiful Code .