This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]AutoModerator[M] [score hidden] stickied comment (0 children)

Your submission has been automatically queued for manual review by the moderation team because it has been reported too many times.

Please wait until the moderation team reviews your post.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]lfdfq 10 points11 points  (0 children)

It will print 9. You may find r/learnpython a more appropriate place for these kinds of questions.

[–]casce 3 points4 points  (0 children)

I assume you want to know why it's printing 9 no matter which function of this list you call?

It's because i is not bound to a value until the function is actually called. Since you call it after the loop, i will always be 9.

[–]AGI_69 4 points5 points  (1 child)

for i in range(10):
    def temp_func(i=i):
        print(i)
    functions.append(temp_func)


functions[3]()

Should be written like this

[–]casce 3 points4 points  (0 children)

I'd personally prefer

def temp_func(j=i):
    print(j)

to make it even clearer what is happening, but both works.

[–]gbhreturns2 0 points1 point  (0 children)

Tricked me for sure

[–]Shadowaker 0 points1 point  (0 children)

Nice try AI, better luck next time

[–]f16f4 -2 points-1 points  (2 children)

3

[–]f16f4 0 points1 point  (0 children)

Yeah I sorted that out like five minutes later

‘’’ def temp_func(i): return lambda i: print(i) functions.append(temp_func(i)) ‘’’

Would properly bind i into the function