3

I know what this does (makes k refer to then actual value instead of last value) but what is this syntax called? Comes from https://stackoverflow.com/a/215326/2375119

funcs = [] 
for k in range(10):
     funcs.append(lambda k = k: k)

>>> funcs[7]()
7 # not 9
0

1 Answer 1

6

The syntax has no name in particular. It's one of the ways of binding closures to their arguments; Python closures are late binding.

That syntax is a way of strapping the current iteratee value to each lambda by passing it as a default argument when creating the lambda. Since default arguments are evaluated when the function is created, the value sticks to the function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.