CS FundamentalsHardProduct-company placement · Python

What does this code print?

What does this code print?
ops = [lambda x: x * k for k in range(1, 4)]
print([op(10) for op in ops])
  1. A. [10, 20, 30]
  2. B. [30, 30, 30]
  3. C. [0, 10, 20]
  4. D. [30, 20, 10]

Correct answer: B. [30, 30, 30]

The lambdas close over the variable k, not its value at creation, and are called after the comprehension ends with k = 3, so each returns 30. A strategy list built this way needs lambda x, k=k: x * k to bind each value.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic