What is the output of this code that compares the time taken by a Python list and a NumPy array to multiply elements by 2?
import time import numpy as np size = 1000000 # Python list multiplication lst = list(range(size)) start_lst = time.time() lst2 = [x * 2 for x in lst] end_lst = time.time() # NumPy array multiplication arr = np.arange(size) start_arr = time.time() arr2 = arr * 2 end_arr = time.time() print(f"List time: {end_lst - start_lst:.5f} seconds") print(f"NumPy time: {end_arr - start_arr:.5f} seconds")
Think about how NumPy uses optimized C code for operations.
NumPy uses optimized low-level code, so operations on arrays are much faster than Python loops over lists.
What is the shape and size of the resulting array after this operation?
import numpy as np arr = np.arange(12).reshape(3,4) result = arr * 3 print(result.shape, result.size)
Multiplying by 3 does not change shape or size.
The shape remains (3,4) and size is total elements 12.
What error does this code raise?
import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([[1, 2], [3, 4]]) result = arr1 + arr2
Check if shapes can be broadcasted for addition.
Shapes (3,) and (2,2) cannot be broadcast together, causing ValueError.
Why is NumPy preferred over pure Python lists for large numerical data processing?
Think about memory and speed advantages.
NumPy arrays use contiguous memory and vectorized operations, making them faster and more memory efficient than lists.
Which statement best explains why NumPy's performance is critical in data science?
Consider the impact of speed on handling big data and machine learning.
NumPy's speed helps data scientists handle large data and train models faster, which is essential for real-world applications.