rth rth -4 years ago 98
Python Question

python why lambda behaves differently when it has constant compare to calls random function

I probably don't understand python's lambda very much. So it confuses me evry time. For example if I have this simple lambda construction with constant, everything works perfect:

>>> f = lambda max,x=0:[ x for x in iter(lambda: x+0.5,max+1.) if x<max ]
>>> f(10)
[0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]

But if I substitute random number generator instead of constant 0.5, it would stuck and never returns back....

>>> f = lambda max,x=0:[ x for x in iter(lambda: x+random.random(),max+1.) if x<max ]
>>> f(10)

Why?! And what to do to avoid it?

Answer Source

iter(lambda: x+0.5,max+1.) stops when the lambda function returns exactly max+1.. The function does return max+1., so the iterator stops there, but that could have gone differently by a fluke of floating-point rounding.

iter(lambda: x+random.random(),max+1.) only stops if the lambda function returns exactly max+1., but this time, it is extremely unlikely that the function will ever return that value. Your list comprehension filters iterator elements forever.

Note that both of your code snippets rely on Python 2 list comprehension variable scope behavior, where the x in the comprehension's for clause is the same as the x from the function the comprehension appears in. That changed in Python 3, so neither of your code snippets work on Python 3.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download