l = [1, 2, 3]
a,b,c = [lambda: n*n for n in l]
a() #=> 9
b() #=> 9
c() #=> 9
Why is this? I expected a(), b(), c(), to be 1, 4, and 9.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
nisn’t in a local closure of the functions.try
This “abuse” of the default parameter causes a local variable called
nto be created for each functionHere is another way to create a closure in Python2
It won’t work in Python3 though because the loop var in the list comprehension isn’t leaked into the global scope
Python3 does a better job of preventing us using a global in the function, so you need to pass a parameter if you want to use a list comprehension