- The preceding statement creates a list A with three elements, each of which is a Lambda anonymous function.
>>> a = [lambda : x for x in range(3)]>>> a[<function <listcomp>.<lambda> at 0x7f79c874ae18>, <function <listcomp>.<lambda> at 0x7f79c874aea0>, <function <listcomp>.<lambda> at 0x7f79c874af28>]>>> a[0]()2>>> a[1]()2>>> a[2]()2>>>
- But why are the return values of all three functions 2?
This is because when a function is created, no parameters are passed.Only when we call three functions at the end will X be passed into the lambda function as a real parameter.At this time, x = 2, so the return values of the three functions are both 2.
- The following example shows the problem clearly.
>>> a = []>>> for i in range(3):... a.append(lambda:i)... >>> a[<function <lambda> at 0x7f79c88022f0>, <function <lambda> at 0x7f79c8802378>, <function <lambda> at 0x7f79c8802400>]>>> a[0]()2>>> a[1]()2>>> a[2]()2>>> i2>>> i = 10>>> a[2]()10>>>
Python's for loop does not introduce new scopes. Therefore, when the lambda function is called, the current I value 2 is actually passed in, when we change the value of I, the return value of the function changes accordingly.
- Let's look at the example below.
>>> a = [lambda x=x : x for x in range(3)]>>> a[0]()0>>> a[1]()1>>> a[2]()2>>> a[2](10)10
This time, during the loop process, the value of X is passed as the default parameter when the function is created, so the output is 0, 1, 2, which is equivalent to using the default parameter.
- If we replace the list with a metagroup, A becomes a generator. Let's look at the example below.
>>> a = (lambda:x for x in range(3))>>> a<generator object <genexpr> at 0x7f79c8f08200>>>> next(a)<function <genexpr>.<lambda> at 0x7f79ca827f28>>>> next(a)<function <genexpr>.<lambda> at 0x7f79c88022f0>>>> next(a)<function <genexpr>.<lambda> at 0x7f79ca827f28>>>> next(a)Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration>>> a = (lambda:x for x in range(3))>>> next(a)()0>>> next(a)()1>>> next(a)()2>>> next(a)()Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration>>>
For more information, see seniusen 」!
Understanding of a = [lambda: X for X in range (3 )]