Counting nested loop iterations
Jeffrey Schwab
jeff at schwabcenter.com
Fri Mar 17 09:23:06 EST 2006
Fredrik Lundh wrote:
> Joel Hedlund wrote:
>
>> I've been thinking about these nested generator expressions and list
>> comprehensions. How come we write:
>>
>> a for b in c for a in b
>>
>> instead of
>>
>> a for a in b for b in c
>>
>> More detailed example follows below.
>>
>> I feel the latter variant is more intuitive. Could anyone please explain the
>> fault of my logic or explain how I should be thinking about this?
>
> out = [a for b in c for a in b]
>
> can be written
>
> out = [a
> for b in c
> for a in b]
>
> which is equivalent to
>
> out = []
> for b in c:
> for a in b:
> out.append(a)
>
> in other words, a list comprehension works exactly like an ordinary for
> loop, except that the important thing (the expression) is moved to the
> beginning of the statement.
Which is utterly counter-intuitive, the opposite of Perl, and remains
one of the most confusing and surprising things I have encountered in
Python so far.
And nobody start yelling that Python is not Perl. We all know Python is
not Perl, nor should it be. If you want different for the sake of
different, though, go try MOO or something. Here:
http://en.wikipedia.org/wiki/Esoteric_programming_language
More information about the Python-list
mailing list