Bird
Raised Fist0
NumPydata~10 mins

Scalar and array broadcasting in NumPy - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Scalar and array broadcasting
Start with scalar and array
↓
Check shapes compatibility
↓
Broadcast scalar to array shape
↓
Perform element-wise operation
↓
Return result array
Broadcasting lets a scalar act like an array of the same shape to do element-wise operations easily.
Execution Sample
NumPy
import numpy as np
arr = np.array([1, 2, 3])
scalar = 5
result = arr + scalar
print(result)
Add a scalar to each element of an array using broadcasting.
Execution Table
StepVariableValue/ShapeActionResult/Output
1arr[1 2 3] (shape (3,))Define array[1 2 3]
2scalar5 (shape ())Define scalar5
3Broadcast scalarBroadcast 5 to [5 5 5]Scalar expanded to array shape[5 5 5]
4Additionarr + broadcasted scalarElement-wise add[6 7 8]
5Print result[6 7 8]Output final array[6 7 8]
💡 All elements added with scalar, operation complete.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
arr[1 2 3][1 2 3][1 2 3][1 2 3]
scalar5Broadcasted to [5 5 5][5 5 5][5 5 5]
resultN/AN/A[6 7 8][6 7 8]
Key Moments - 3 Insights
Why can we add a scalar to an array directly?
Because numpy broadcasts the scalar to match the array's shape, making element-wise addition possible as shown in step 3 of the execution_table.
Does the scalar change its original value during broadcasting?
No, the scalar value stays the same; broadcasting just treats it as if it were an array of the same shape without copying data, as seen in variable_tracker after step 3.
What happens if the array has multiple dimensions?
The scalar still broadcasts to match the full shape of the array, allowing element-wise operations across all elements, similar to the simple 1D example but extended to more dimensions.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the shape of the broadcasted scalar?
A(3,)
B(1,)
C()
D(5,)
💡 Hint
Check the 'Value/Shape' column at step 3 in the execution_table.
At which step does the element-wise addition happen?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look for the 'Action' describing addition in the execution_table.
If the scalar was replaced by an array [5, 5, 5], how would the broadcast step change?
AScalar would broadcast to shape (3,)
BNo broadcasting needed, direct element-wise addition
CBroadcasting would fail due to shape mismatch
DScalar would broadcast to shape ()
💡 Hint
Refer to how broadcasting works when both operands have the same shape.
Concept Snapshot
Scalar and array broadcasting in numpy:
- Scalars act like arrays of matching shape
- Enables element-wise operations without explicit loops
- Scalar is virtually expanded to array shape
- Efficient and memory-friendly
- Works with arrays of any dimension
Full Transcript
This visual execution shows how numpy broadcasts a scalar to an array's shape to perform element-wise addition. Starting with an array [1, 2, 3] and a scalar 5, numpy treats the scalar as if it were [5, 5, 5]. Then it adds each element of the array to 5, resulting in [6, 7, 8]. Variables track the scalar and array values before and after broadcasting. Key moments clarify why broadcasting works and that the scalar value itself does not change. The quiz tests understanding of broadcasting shape, operation step, and behavior when replacing scalar with an array.

Practice

(1/5)
1. What happens when you add a scalar to a NumPy array using broadcasting?
easy
A. The scalar is added to each element of the array.
B. The scalar is ignored and the array remains unchanged.
C. An error occurs because shapes do not match.
D. The scalar replaces all elements in the array.

Solution

  1. Step 1: Understand scalar and array addition

    A scalar is treated as an array with no dimensions and can be added to each element of the array.
  2. Step 2: Apply broadcasting rules

    Broadcasting repeats the scalar value to match the shape of the array, adding it element-wise.
  3. Final Answer:

    The scalar is added to each element of the array. -> Option A
  4. Quick Check:

    Scalar + array = element-wise addition [OK]
Hint: Scalar acts like a single value added to all elements [OK]
Common Mistakes:
  • Thinking scalar is ignored
  • Expecting shape mismatch error
  • Assuming scalar replaces array
2. Which of the following is the correct syntax to add scalar 5 to a NumPy array arr?
easy
A. arr.add(5)
B. arr + 5
C. add(arr, 5)
D. arr + [5]

Solution

  1. Step 1: Recall NumPy scalar addition syntax

    Adding a scalar to an array is done simply by using the plus operator: arr + scalar.
  2. Step 2: Evaluate options

    arr + 5 uses arr + 5, which is correct. arr.add(5) is invalid syntax. add(arr, 5) is not a NumPy function. arr + [5] tries to add a list, which changes behavior.
  3. Final Answer:

    arr + 5 -> Option B
  4. Quick Check:

    Use arr + scalar for scalar addition [OK]
Hint: Use plus operator directly for scalar addition [OK]
Common Mistakes:
  • Using method .add() which doesn't exist
  • Passing scalar inside a list
  • Using non-existent add() function
3. What is the output of the following code?
import numpy as np
arr = np.array([1, 2, 3])
result = arr * 3
print(result)
medium
A. [3 3 3]
B. [1 2 3 3 6 9]
C. Error due to shape mismatch
D. [3 6 9]

Solution

  1. Step 1: Understand scalar multiplication with array

    Multiplying an array by a scalar multiplies each element by that scalar.
  2. Step 2: Calculate element-wise multiplication

    Each element in [1, 2, 3] is multiplied by 3, resulting in [3, 6, 9].
  3. Final Answer:

    [3 6 9] -> Option D
  4. Quick Check:

    Array * scalar = element-wise multiplication [OK]
Hint: Multiply each element by scalar directly [OK]
Common Mistakes:
  • Expecting concatenation instead of multiplication
  • Thinking output is repeated elements
  • Assuming error due to shape mismatch
4. Identify the error in this code snippet:
import numpy as np
arr = np.array([1, 2, 3])
scalar = np.array([5])
result = arr + scalar
print(result)
medium
A. Output is [1 2 3 5]
B. Error because scalar is an array, not a number
C. No error; output is [6 7 8]
D. Error due to shape mismatch

Solution

  1. Step 1: Check shapes of arrays

    arr shape is (3,), scalar shape is (1,). Broadcasting allows (1,) to expand to (3,).
  2. Step 2: Apply broadcasting addition

    Each element of arr is added to 5, resulting in [6, 7, 8].
  3. Final Answer:

    No error; output is [6 7 8] -> Option C
  4. Quick Check:

    Broadcasting works with (3,) + (1,) arrays [OK]
Hint: Arrays with shape (n,) and (1,) broadcast correctly [OK]
Common Mistakes:
  • Assuming scalar must be a plain number
  • Thinking shape mismatch causes error
  • Expecting concatenation instead of addition
5. Given a 2D array arr = np.array([[1, 2, 3], [4, 5, 6]]), what is the result of arr + np.array([10, 20, 30])?
hard
A. [[11 22 33] [14 25 36]]
B. [[11 12 13] [14 15 16]]
C. Error due to shape mismatch
D. [[10 20 30] [10 20 30]]

Solution

  1. Step 1: Analyze shapes for broadcasting

    arr shape is (2,3), and np.array([10, 20, 30]) shape is (3,). The second array broadcasts across rows.
  2. Step 2: Perform element-wise addition row-wise

    Each row of arr adds the vector [10, 20, 30] element-wise, resulting in [[11, 22, 33], [14, 25, 36]].
  3. Final Answer:

    [[11 22 33] [14 25 36]] -> Option A
  4. Quick Check:

    Broadcast vector added to each row [OK]
Hint: Vector added to each row in 2D array [OK]
Common Mistakes:
  • Expecting error due to different shapes
  • Adding vector only to first row
  • Confusing addition with concatenation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard