Recall & Review
beginner
What is vectorization in the context of numpy?
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?
✗ Incorrect
Vectorization lets you perform operations on whole arrays without writing loops.
Which of these is a vectorized operation in numpy?
✗ Incorrect
Adding two arrays directly with '+' is vectorized.
Why is vectorized numpy code usually faster?
✗ 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?
✗ Incorrect
Numpy raises a ValueError if shapes are incompatible for broadcasting.
Which numpy function can help apply a vectorized operation to each element?
✗ 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.