Bird
0
0

What will be the output of the following code snippet?

medium📝 Predict Output Q4 of 15
NumPy - Fundamentals
What will be the output of the following code snippet?
import numpy as np
import time

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

start = time.time()
sum_lst = sum(lst)
end = time.time()
print(round(end - start, 3))

start = time.time()
sum_arr = np.sum(arr)
end = time.time()
print(round(end - start, 3))
Asum(lst) will be faster than np.sum(arr)
BBoth sum(lst) and np.sum(arr) will take roughly the same time
CThe time taken by np.sum(arr) will be significantly less than sum(lst)
DThe code will raise an error because np.sum cannot sum arrays
Step-by-Step Solution
Solution:
  1. Step 1: Understand sum on list

    Python's built-in sum iterates over the list in Python bytecode, which is slower.
  2. Step 2: Understand np.sum on array

    NumPy's sum is implemented in optimized C code and operates on contiguous memory.
  3. Final Answer:

    The time taken by np.sum(arr) will be significantly less than sum(lst) -> Option C
  4. Quick Check:

    NumPy sum is faster due to optimized implementation [OK]
Quick Trick: np.sum is faster than Python sum on large numeric data [OK]
Common Mistakes:
  • Assuming Python sum is faster due to simplicity
  • Believing np.sum raises errors on arrays
  • Thinking both methods have identical performance

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes