list comprehension question
gallium.arsenide at gmail.com
Wed May 6 08:10:34 CEST 2009
On May 5, 11:36 pm, alex23 <wuwe... at gmail.com> wrote:
> Apart from the presence of 'item' at the beginning of the
> list comprehension as opposed to 'b.append(item)' at the
> end of the for-loop, how exactly does the listcomp force
> you to "bounce [..] back and forth" to follow the logic?
It's precisely the fact that the item is at the beginning which is the
main instigator of the bounce. To tranlate
[f(x) for x in a]
into a loop, you start in the middle, work your way toward the right,
then bounce back to the left.
I think some of us, perhaps subconsciously, get used to reading that
small chunk on the right, then bouncing left. See enough small, flat
LCs, and we may be conditioned to think that the general rule is to
start with that small chunk on the right and bounce left.
When confronted with a long, nested LC then, some of us have the
instinct to read the rightmost chunk, then bounce left to the next-
rightmost chunk, etc.
Essentially, if you see [B A] over and over and over again, when
finally confronted with LCs of more "elements", it's not immediately
clear that the pattern of increasing nestedness is
[B A] => [C A B] => [D A B C] => etc.
[B A] => [C B A] => [D C B A] => etc.
Maybe we're wired wrong, but there are many of us who find the second
pattern more logical, which is why it is so easy for us to mess up the
order of the nesting in a more complex LC.
More information about the Python-list