ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
data = [4, 7, 1, 9]
best = 0
hi = [best := x for x in data if x > best]
print(hi, best, "x" in globals())
  1. A. [4, 7, 9] 9 False
  2. B. [4, 7, 1, 9] 0 False
  3. C. [4, 7, 9] 0 True
  4. D. [4, 7, 9] 9 True

Correct answer: A. [4, 7, 9] 9 False

An assignment expression inside a comprehension binds the name in the ENCLOSING scope, so each kept x updates the outer best, and the next test compares against it: 4 > 0, 7 > 4, 1 fails, 9 > 7. best ends as 9. The loop variable x itself stays local to the comprehension, so it does not appear in globals().

More Python Programming questions

Exams that ask this topic