Explanation of this Python language feature? [x for x in x for x in x] (to flatten a nested list)

Ian Kelly ian.g.kelly at gmail.com
Sun Mar 23 03:46:28 CET 2014


On Sat, Mar 22, 2014 at 6:32 PM, Rhodri James <rhodri at wildebst.org.uk> wrote:
> On Sat, 22 Mar 2014 05:26:26 -0000, Rustom Mody <rustompmody at gmail.com>
> wrote:
>
>> Well almost...
>> Except that the 'loop' I am talking of is one of
>> def loop():
>>      return [yield (lambda: x) for x in [1,2,3]]
>> or
>>      return (yield (lambda: x) for x in [1,2,3])
>> or just plain ol
>>      (lambda x:  for x in [1,2,3])
>> IOW loop is an imperative construct, comprehensions are declarative
>
>
> I'm sorry, you've made a logical leap too far here.  I understand loops
> being imperative, but how are comprehensions declarative?  What do they
> declare that the loop equivalent doesn't.

I'm with Rustom on this point.  A list comprehension is a syntax for
building a list by declaring a transformation from some other iterable
object.  Forget comprehensions for a moment and think of literals.
Would you not consider this to be declarative?

    x = [1, 2, 3]

A comprehension is syntactically similar to a literal, with just a
different type of construction in mind.

Where I disagree is on the question of whether Python should therefore
break its established closure rules for lambdas that are nested inside
comprehensions versus functions that are not.  It breaks the
equivalence between comprehensions and loops, and to my mind it
introduces significant complexity for relatively little gain.



More information about the Python-list mailing list