I found an interesting issue why trying to do a the following for a code golf challenge:
>>> f=lambda s,z=len(s): 5+z
>>> f("horse")
11 #Expected 10
>>>
>>> def g(s,z=len(s)):
... print "z: ", z
... print "sum: ", 5+z
...
>>> g("horse")
z: 6
sum: 11
>>>
>>> len("horse") + 5 #Expected function operation
10
Creating the function both ways seems to initialize z
as 6
instead of the expected 5
, why does this happen?
The python docs have a page that explains this
Python’s default arguments are evaluated once when the function is defined, not each time the function is called
In your case, s
must have already been bound to a string of length 6 before you created the lambda function. When python evaluated the lambda definition with z=len(s)
, it evaluated to z=6
. It doesn't get processed again each time you call the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With