Bird
0
0

Consider this code:

medium📝 Predict Output Q5 of 15
NumPy - Fundamentals
Consider this code:
import numpy as np
import time

lst = list(range(1000000))
arr = np.array(lst)

start = time.time()
squared_lst = [x**2 for x in lst]
end = time.time()
print(round(end - start, 3))

start = time.time()
squared_arr = arr ** 2
end = time.time()
print(round(end - start, 3))

What is the expected output behavior?
AList comprehension will be faster than NumPy array squaring.
BSquaring the NumPy array will be much faster than the list comprehension.
CBoth methods will take the same time.
DThe code will raise a ValueError.
Step-by-Step Solution
Solution:
  1. Step 1: Understand vectorized operations

    NumPy arrays support vectorized operations like arr ** 2 which run in optimized C code.
  2. Step 2: Compare with list comprehension

    List comprehension runs Python loops and is slower for large data compared to NumPy vectorized operations.
  3. Final Answer:

    Squaring the NumPy array will be much faster than the list comprehension. -> Option B
  4. Quick Check:

    Vectorized NumPy ops faster than Python loops [OK]
Quick Trick: Use NumPy vectorized ops for faster element-wise math [OK]
Common Mistakes:
  • Thinking list comprehension is faster due to simplicity
  • Expecting identical performance
  • Assuming code raises errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes