In this article I list out some tricks in Python programming. I will keep updating this post each time I find anything interesting.
Traps in default value
1 | |
The code seem fine because every time the function itself would initialize an empty list and append a new value to it. However the result is very surprising:
1 | |
This is because the default value, which is an empty list here keeps using the same address in the memory. Whenever value is specified for res, it simply use that same list on the specific memory address. These three list, l1, l2 and l3 are thus actually manipulating the same list.
The correct way to do this is as follows, which would kinda avoid this problem.
1 | |
Python closure
1 | |
The result is surprising because the functions in another function will not check the value of i until it runs. So it only looks at the value of i when all three make_square functions are ready, at which moment the value of i is already 3.
One way to avoid the problem is to pass the index value explicitly to the function.
1 | |
More details about closure in Python are available here.
Enumerate
To float before division
from __future__ import division