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

Rhodri James rhodri at wildebst.org.uk
Sat Mar 22 20:32:22 EDT 2014


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.

You've made a great deal of the "for" in a comprehension not having the  
same meaning as the "for" in a loop.  That may well be true in the  
equivalent Haskell constructs (I don't speak or write Haskell), but I  
think you are wrong in Python.  If so, please stop trying to write Haskell  
in Python; you'll be as happy as the friend of mine I've finally persuaded  
to stop writing Fortran in Python, I promise!

-- 
Rhodri James *-* Wildebeest Herder to the Masses



More information about the Python-list mailing list