Bird
0
0

The following code tries to multiply each element of a Python list by 2 using NumPy syntax but fails. What is the error?

medium📝 Debug Q14 of 15
NumPy - Fundamentals
The following code tries to multiply each element of a Python list by 2 using NumPy syntax but fails. What is the error?
lst = [1, 2, 3, 4]
result = lst * 2
print(result)
AIt raises a TypeError because lists cannot be multiplied.
BIt prints [2, 4, 6, 8] as expected.
CIt prints [1, 2, 3, 4, 1, 2, 3, 4] instead of doubling values.
DIt raises a NameError because 'lst' is undefined.
Step-by-Step Solution
Solution:
  1. Step 1: Understand list multiplication behavior

    Multiplying a Python list by 2 repeats the list elements, it does not multiply each element.
  2. Step 2: Compare with NumPy array behavior

    NumPy arrays multiply each element by 2, but Python lists just repeat the list when multiplied by an integer.
  3. Final Answer:

    It prints [1, 2, 3, 4, 1, 2, 3, 4] instead of doubling values. -> Option C
  4. Quick Check:

    List * 2 repeats list, does not multiply elements = C [OK]
Quick Trick: List * 2 repeats list; use np.array for element-wise multiply. [OK]
Common Mistakes:
  • Expecting element-wise multiplication on lists
  • Thinking it raises an error
  • Confusing list and array multiplication

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes