0
0
NumPydata~5 mins

Vectorization over loops in NumPy - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AImporting numpy
BUsing numpy arrays
CUsing functions
DWriting explicit loops over array elements
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)
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
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
Which numpy function can help apply a vectorized operation to each element?
Anp.loop
Bnp.for_each
Cnp.vectorize
Dnp.iter
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.