unintuitive for-loop behavior

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Mon Oct 3 04:42:12 EDT 2016


Antoon Pardon writes:

> Op 02-10-16 om 07:59 schreef Rustom Mody:
>>
>> You are explaining the mechanism behind the bug. Thanks. The bug
>> remains.  My new car goes in reverse when I put it in first gear but
>> only on full-moon nights with the tank on reserve when the left light
>> is blinking The engineer explains the interesting software bug in the
>> new PCB.  Interesting. But the bug remains
>>
>> Likewise here:
>>
>> [2 ** i for i in[1,2]] == [2**1, 2**2]
>>
>> yet this fails 
>>
>> [lambda x: x + i for i in [1,2]] == [lambda x:x+1, lambda x:x=2]
>>
>> is a bug for anyone including the OP of this thread

(That x=2 should be x+2.)

(And that == for functions needs to be understood mathematically. In
Python, even (lambda : 1) == (lambda : 1) may (must?) be False.)

> I once suggested that a list comprehension like [<exp> for i in
> <iterator>] should be implemented as [(lambda i:<exp>)(i) for i in
> <iterator>].
>
> As far a I can see, it would behave as expected in all cases.

It's strictly circular as-is (the latter is an instance of the former),
and it needs spelled-out a bit in order to cover comprehensions of
multiple variables. I like it anyway.

On the other hand, fortunately, it's simple to *do* this in practice
when the need arises, without waiting for anyone to change the
language. (So is the default-parameter trick.)



More information about the Python-list mailing list