Jan 12, 2022
I’m always writing list comprehensions in Python. Once I tried to get a list of
lambdafunctions using a list comprehension, and later I found that the functions are all the same - they were supposed to be different.
The case was very simple:
phi = [lambda x: x**i for i in range(5)]
We would expect the i-th term in this list return a degree-i polynomial of the input, this is pretty intuitive. However, when tested, suprisingly -
>>> phi(10) 10000 >>> phi(10) 10000 >>> phi(10) 10000
They are supposed to return 1, 10 and 100. What happened?
This is actually something covered in the official document since Python 3.4:
Programming FAQ - Python 3.4.10 documentation
Yes. The pdb module is a simple but adequate console-mode debugger for Python. It is part of the standard Python library, and is . You can also write your own debugger by using the code for pdb as an example.
ivariable here is defined outside the scope of the
lambdafunctions. In another sense, all these lambda functions here are actually the same, but in diffenent addresses. When called, they all search for variable
iin their outer scope, and return
x**i. This means all of them will be referencing the last
iin loop, no matter it’s a list comprehension or a
lambdafunction or a proper function.
The solution is also simple, use a default parameter. In this way the
is will be recorded when initializing the function in its scope, and it will work as we wish.
phi = [lambda x, deg=i: x**deg for i in range(5)] >>> phi(10) 1 >>> phi(10) 10 >>> phi(10) 100