Bird
0
0

The code below aims to compare performance of sum on a Python list and a NumPy array:

medium📝 Debug Q7 of 15
NumPy - Fundamentals
The code below aims to compare performance of sum on a Python list and a NumPy array:
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(end - start)

start = time.time()
sum_arr = np.sum(arr)
end = time.time()
print(end - start)

But the output shows the NumPy sum is slower. What is a possible reason?
APython sum is always faster than NumPy sum.
BThe NumPy array was created with dtype=object, causing slow operations.
CThe list contains strings, so sum is faster.
DThe code has a syntax error.
Step-by-Step Solution
Solution:
  1. Step 1: Understand dtype impact on NumPy speed

    If the NumPy array has dtype=object, operations fall back to slower Python loops.
  2. Step 2: Compare with Python sum

    Python sum on integers is fast; NumPy sum on object dtype is slower, explaining the result.
  3. Final Answer:

    The NumPy array was created with dtype=object, causing slow operations. -> Option B
  4. Quick Check:

    Object dtype slows NumPy operations [OK]
Quick Trick: Check NumPy array dtype for performance issues [OK]
Common Mistakes:
  • Assuming Python sum is always faster
  • Ignoring dtype when creating arrays
  • Thinking code syntax causes slowdown

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes