LearnFrenzy
Sign in Take a free test

Lambda Functions · Find the Error · Question 4

Bug: every handler reports the last item Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Each handler should print its own label. Which statement correctly identifies the bug?

main.py
handlers = []
for label in ["Save", "Open", "Exit"]:
    handlers.append(lambda: "clicked " + label)
print([h() for h in handlers])
  • A append() copies the last lambda three times
  • B Strings cannot be used in lambdas
  • C The list comprehension calls the wrong handler
  • D The lambdas look up label when called, after the loop ended on "Exit"; capture it with lambda label=label: … Correct
Correct Answer: Option D

Late binding: free variables are resolved at call time. functools.partial also captures the current value.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links