Weird closure behavior in python

0 votes
Here is a simple code I have been dealing with :

def get():
    return [lambda: i for i in [1, 2, 3]]

for f in get():
    print(f())

The output to this code is 3 but how does it work internally?
Feb 2, 2019 in Python by ana1504.k
• 7,910 points
850 views

1 answer to this question.

0 votes
Closures don't refer to variables but rather to scopes. Since the last value of i in its scope is '3', all three closures return the same. To "lock" the current value of a variable, create a new scope just for it:

def get() : return [ (lambda x: lambda: x)(i) for i in [ 1, 2, 3 ] ]
for f in get() : print( f() )
answered Feb 2, 2019 by SDeb
• 13,300 points

Related Questions In Python

+3 votes
7 answers

How can I rename a file in Python?

yes, you can use "os.rename" for that. ...READ MORE

answered Mar 31, 2018 in Python by DareDev
• 6,890 points
20,008 views
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,440 points
1,305 views
+2 votes
3 answers

what is the practical use of polymorphism in Python?

Polymorphism is the ability to present the ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,440 points
4,881 views
+2 votes
2 answers

Error while printing hello world in python.

You must be trying this command in ...READ MORE

answered Mar 31, 2018 in Python by GandalfDwhite
• 1,320 points
6,402 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
0 votes
1 answer

Indentation of Python in Notepad++

To indent the block, select the entire ...READ MORE

answered Sep 18, 2018 in Python by SDeb
• 13,300 points
2,349 views
0 votes
1 answer

Print C format in Python

For printf- style formatting and special case ...READ MORE

answered Sep 18, 2018 in Python by SDeb
• 13,300 points
1,005 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP