List comprehensions

Albert Hofkamp hat at se-46.wpa.wtb.tue.nl
Tue Dec 21 11:54:16 EST 1999


On Tue, 21 Dec 1999 11:05:57 -0500, Mike Fletcher <mfletch at tpresence.com> wrote:
>How about:
>
>[ (x*2,x/2,x**y), 
>	for x in somelist, 
>	for y in someotherlist,
>]

>Which seems to take care of most of the problems, it's got a decent sound
>(especially with the commas present), is unambiguous as far as I can see,
>and provides for parallel iteration.  While I prefer the explicit syntax of

Huh, I may be missing something, but to me it is nested in each other.
Note that there is no real reason why two for-loops would not be nested
in each other. For example, to create a list of tuples containing all
combinations of elements of X:

 [ (x,y), for x in X, for y in X ]

Compare it with

 [ x | x <- xs, x>5 ]

To most people (and me included), this is

  res=[]
  for x in xs:
    if x>5:
      res = res + [x]

In other words, from left to right, each element is nested in the previous one.
Imho, that principle is easy to explain and very intuitive for users
(you almost don't have to explain it).

With parallel iteration, you are doing two things at a time.
If you want to be able to do this in Python (a new question !!),
then imho you'd need a single language construct which looks like 'see,
I am iterating over both lists here, watch out !'

For example,

 [ (x,y) | x and y <- xs and ys ]

or in Pythonese:

 [ (x,y), for x and y in xs and ys ]

except that the 'and' puts the user on the wrong foot, as he is
automagically associating the construct with a condition.
Also, the 'in', which is more or less the important part here, is not
quite visible any more.

PS I'd like to have a stronger visual separation between the result
   expression, and the iterations and conditions, so '|' looks better to me
   than ',' .
   This is especially true if you do not start with an iteration, like in

   [ x>6, x>5 ]

   (Bonus-points for the people who understand what the result is :-) )

Albert
---
Look ma, windows without Windows !!



More information about the Python-list mailing list