← Back to context

Comment by d0mine

11 days ago

all one needs to understand is that there are names that refer to objects in Python. Nothing is passed by value.

The closure returns whatever object the name refers at the moment. That is all.

    def loop():
        for i in range(10):
             yield lambda j=i:  j

`j` refers to the same object (int) `i` refers to at the time of the lambda creation (the desired result). `j` is local to the lambda (each lambda has its own local namespace).

Just `lambda: i` code would result in an object that `i` refers to at the time of calling the lambda (`i` name is not local to the lambda).

https://docs.python.org/3/faq/programming.html#why-do-lambda...