Vectorization means performing operations on whole arrays at once instead of using loops to process elements one by one. It makes code faster and simpler.
Click to reveal answer
beginner
Why is vectorization faster than using loops in numpy?
Because numpy uses optimized C code and parallel processing under the hood, it can handle whole arrays at once, avoiding slow Python loops.
Click to reveal answer
beginner
Example: How to add two arrays element-wise using vectorization?
Use the '+' operator directly on numpy arrays. For example, if a = np.array([1,2]) and b = np.array([3,4]), then a + b gives np.array([4,6]).
Click to reveal answer
intermediate
What is a common mistake when switching from loops to vectorized numpy code?
Trying to use Python loops inside numpy operations or forgetting that numpy operations work element-wise on arrays, not on single elements.
Click to reveal answer
beginner
How does vectorization improve code readability?
Vectorized code is shorter and clearer because it expresses operations on whole arrays directly, avoiding complex loop structures.
Click to reveal answer
What does vectorization help you avoid in numpy?
AImporting numpy
BUsing numpy arrays
CUsing functions
DWriting explicit loops over array elements
✗ Incorrect
Vectorization lets you perform operations on whole arrays without writing loops.
Which of these is a vectorized operation in numpy?
Afor i in range(len(a)): c[i] = a[i] + b[i]
Bc = a + b
Cwhile i < len(a): c[i] = a[i] + b[i]
Dc = []
for x in a:
c.append(x)
✗ Incorrect
Adding two arrays directly with '+' is vectorized.
Why is vectorized numpy code usually faster?
AIt uses optimized C code and avoids Python loops
BIt uses Python loops
CIt uses more memory
DIt runs slower but looks nicer
✗ Incorrect
Numpy vectorization uses fast C code and avoids slow Python loops.
What happens if you try to add two numpy arrays of different shapes without broadcasting?
AIt raises an error
BIt returns zeros
CIt ignores the smaller array
DIt works fine
✗ Incorrect
Numpy raises a ValueError if shapes are incompatible for broadcasting.
Which numpy function can help apply a vectorized operation to each element?
Anp.loop
Bnp.for_each
Cnp.vectorize
Dnp.iter
✗ Incorrect
np.vectorize wraps a function to apply it element-wise on arrays.
Explain in your own words why vectorization is preferred over loops in numpy.
Think about how numpy handles arrays internally.
You got /4 concepts.
Describe how you would convert a loop that adds two arrays element-wise into a vectorized numpy operation.
Focus on replacing the loop with a single numpy expression.
You got /4 concepts.
Practice
(1/5)
1. What is the main advantage of using vectorization in numpy instead of loops?
easy
A. It makes the code run faster by doing many operations at once.
B. It uses more memory but slows down the code.
C. It makes the code harder to read and understand.
D. It requires writing more lines of code.
Solution
Step 1: Understand vectorization concept
Vectorization means applying operations on whole arrays at once, not one element at a time.
Step 2: Compare speed and simplicity
This approach uses optimized numpy functions that run faster than explicit loops.
Final Answer:
It makes the code run faster by doing many operations at once. -> Option A
Quick Check:
Vectorization = faster code [OK]
Hint: Vectorization speeds up code by handling arrays at once [OK]
Common Mistakes:
Thinking vectorization slows code
Believing vectorization needs more code
Confusing vectorization with loops
2. Which of the following numpy codes correctly replaces a loop to add 5 to each element in array a?
easy
A. a + 5
B. for i in a: i = i + 5
C. np.add(a, 5, out=a)
D. a.append(5)
Solution
Step 1: Identify vectorized addition
Using np.add(a, 5, out=a) adds 5 to every element in array a efficiently.
Step 2: Check other options
a + 5 works but returns a new array, for i in a: i = i + 5 does not change a, and a.append(5) is invalid for numpy arrays.
Final Answer:
np.add(a, 5, out=a) -> Option C
Quick Check:
np.add = vectorized add [OK]
Hint: Use numpy functions like np.add for vectorized operations [OK]
Common Mistakes:
Using loops that don't modify array
Trying list methods on numpy arrays
Confusing array addition with append
3. What is the output of this code?
import numpy as np
arr = np.array([1, 2, 3])
result = arr * 2
print(result)
medium
A. [2 4 6]
B. [1 2 3 1 2 3]
C. [3 4 5]
D. Error: cannot multiply array by int
Solution
Step 1: Understand array multiplication
Multiplying a numpy array by a number multiplies each element by that number.
Step 2: Calculate element-wise multiplication
Each element in [1, 2, 3] is multiplied by 2, resulting in [2, 4, 6].
Final Answer:
[2 4 6] -> Option A
Quick Check:
Array * number = element-wise multiply [OK]
Hint: Array * number multiplies each element [OK]
Common Mistakes:
Thinking it concatenates arrays
Expecting an error on multiplication
Confusing element-wise with matrix multiply
4. Identify the error in this code that tries to add 10 to each element of arr using a loop:
import numpy as np
arr = np.array([1, 2, 3])
for i in arr:
i = i + 10
print(arr)
medium
A. Syntax error in for loop.
B. Loop variable i does not modify original array elements.
C. Array arr is not defined.
D. Cannot add integer to numpy array elements.
Solution
Step 1: Understand loop variable behavior
Variable i is a copy of each element, so changing i does not change arr.
Step 2: Explain why array remains unchanged
The original array arr stays the same because the loop does not assign back to array elements.
Final Answer:
Loop variable i does not modify original array elements. -> Option B
Quick Check:
Loop var copy ≠ array change [OK]
Hint: Loop vars are copies; assign to array to change [OK]
Common Mistakes:
Assuming loop changes array automatically
Thinking syntax error exists
Believing numpy disallows int addition
5. You have a numpy array data = np.array([1, 2, 3, 4, 5]). You want to create a new array where each element is squared if it is even, otherwise doubled. Which vectorized code achieves this?
hard
A. data * 2 if data % 2 else data ** 2
B. [x**2 if x%2==0 else x*2 for x in data]
C. for i in range(len(data)): data[i] = data[i]**2 if data[i]%2==0 else data[i]*2
D. np.where(data % 2 == 0, data**2, data*2)
Solution
Step 1: Understand vectorized conditional with np.where
np.where(condition, x, y) returns array choosing x where condition is true, else y.
Step 2: Apply condition for even and odd elements
Condition data % 2 == 0 checks even numbers; squares them, else doubles.
Step 3: Check other options
[x**2 if x%2==0 else x*2 for x in data] uses list comprehension (not vectorized), C uses loop (not vectorized), D is invalid syntax.
Final Answer:
np.where(data % 2 == 0, data**2, data*2) -> Option D
Quick Check:
np.where = vectorized if-else [OK]
Hint: Use np.where for vectorized if-else conditions [OK]
Common Mistakes:
Using loops or list comprehensions instead of vectorization
Writing invalid syntax for conditional operations
Confusing element-wise operations with scalar
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.