0
0
NumPydata~5 mins

Scalar and array broadcasting in NumPy - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is broadcasting in numpy?
Broadcasting is a way numpy allows operations between arrays of different shapes by automatically expanding the smaller array to match the shape of the larger one without copying data.
Click to reveal answer
beginner
How does numpy handle operations between a scalar and an array?
Numpy treats the scalar as if it were an array of the same shape as the other array, with all elements equal to the scalar, allowing element-wise operations.
Click to reveal answer
beginner
Example: What is the result of np.array([1, 2, 3]) + 5?
The result is np.array([6, 7, 8]) because the scalar 5 is broadcast to each element of the array and added element-wise.
Click to reveal answer
intermediate
What are the rules numpy uses to decide if broadcasting is possible?
Numpy compares shapes from right to left. Dimensions must be equal or one of them must be 1. If these conditions hold for all dimensions, broadcasting works.
Click to reveal answer
beginner
Why is broadcasting useful in data science?
Broadcasting lets you write simple code to perform operations on arrays of different sizes efficiently, saving memory and making calculations faster.
Click to reveal answer
What happens when you add a scalar to a numpy array?
AThe scalar is added to each element of the array
BAn error occurs because shapes differ
CThe scalar replaces the array elements
DOnly the first element of the array is added to the scalar
Which of these shape pairs can be broadcast together? (3,1) and (1,4)
AYes, because dimensions are compatible
BNo, because shapes differ
COnly if both are 1D arrays
DOnly if one shape is (3,4)
What does broadcasting NOT do?
AAutomatically expand arrays without copying data
BMake element-wise operations possible
CAllow operations on arrays of different shapes
DChange the original array's shape permanently
If you have an array shape (5,) and a scalar, what will be the shape of the result after addition?
A(5,5)
B(1,)
C(5,)
D()
Which of these can you use to check the shape of an array?
Anp.length()
Barr.shape
Cnp.size()
Dnp.dim()
Explain in your own words how numpy uses broadcasting when adding a scalar to an array.
Think about how a single number can be added to many numbers in a list.
You got /4 concepts.
    Describe the rules numpy follows to decide if two arrays can be broadcast together.
    Focus on how numpy checks each dimension starting from the end.
    You got /4 concepts.