Practice mode Python

What is the output of the following Python code? funcs = ; print()

Correct answer C. [2, 2, 2]

Explanation

Closures capture variables, not values, and look them up when called. All three lambdas refer to the same comprehension variable i, which is 2 once the loop has finished, so each returns 2. Binding the current value with a default argument, as in lambda i=i: i, gives [0, 1, 2].

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.