Broadcasting means replicating a multidimensional array along some of its singleton dimensions to match the size of another array. This happens automatically for Numpy arrays when arithmetic operators are applied to them.
For example, to generate a 10×10 multiplication table you can use
import numpy
t=numpy.arange(1,11)
print(t*t[:,None]) # Or replace t[:,None] by [*zip(t)]
Try it online!
Here t
is created as the Numpy array [1, 2, ..., 10]
. This has shape (10,), which is equivalent to (1,10). The other operand array, t[:,None]
, has size (10,1). Multiplying the two arrays implicitly replicates them, so they behave as if they both had shape (10,10). The result, which also has shape (10,10), contains the products for all pairs of entries in the original arrays.
Note that
– Andras Deak – 2018-02-24T12:31:23.833pylab
is justmatplotlib.pyplot
+numpy
in a deprecated common namespace. Thenumpy
part ofpylab
is trivial in the sense that their imports have the same number of bytes, so only plotting stuff could additionaly come frompylab
, but I suspect that's not what you had in mind with your question.2@AndrasDeak, I'm aware that using pylab is considered bad practice, but very little in codegolf can be considered good practice. Pylab directly includes parts of many
numpy
packages. For examplepylab.randint
is valid where numpy would requirenumpy.random.randint
. So for golfingpylab
should provide shorter code. – user2699 – 2018-02-24T15:58:28.2631I'm aware that deprecation is not a problem, my point was that it also doesn't give an advantage. I simply didn't realize that subpackages were also loaded into the pylab namespace like that! So sorry, you're perfectly right :) – Andras Deak – 2018-02-24T16:08:25.143