List comprehensions

Magnus L. Hetland mlh at vier.idi.ntnu.no
Mon Dec 20 09:28:28 EST 1999


Greg Ewing <greg.ewing at compaq.com> writes:

> skaller wrote:
> > 
> > What is the proposed syntax for list comprehensions?
> 
> The one my patch currently implements is:
> 
>    list_comprehension :== '[' expr iterator... ']'
>    iterator :== 'for' target 'in' expr | 'if' expr

Have you looked into adding separators (like "and") between the
iterators yet? (You *did* see that as a possibility, didn't you?)

After all, that is what is done in math, more or less... (Either using
a logical and or a comma.)

  (Quasi-LaTeX)
  P = {(x,y) | x \in X \and y \in Y}

  (Quasy-Python)
  P = [(x, y) for x in X and for y in Y]

The use of "and for" (since "and" would be ambiguous) seems a bit
verbose -- which is something that speeks for your current format...

  P = [(x, y) for x in X for y in Y]

Hm... Do the iterators work in parallel? Or would I end up with a
Cartesian  product here? Logically (or intuitively), the above
expression would seem (to me) to mean:

  P = []
  for x in X:
      for y in Y:
          P.append((x,y))

which is, come to think of it, exactly what it means. Cool! But what
could the version with "and" mean, then? Since it is a bit more
verbose, it should probably be something less often used... Hm. It
seems to me to mean something like:

  P = []
  for i in range(min(len(X),len(Y))):
      x, y = X[i], Y[i]
      P.append(x,y)

i.e. parallel iteration, which can also be quite useful sometimes.

(Maybe X and Y should be of equal length... And I'm not quite sure
what would happen if you introduce if-clauses in each of the
iterators...)

Anyway... I guess my conclusion is that I withdraw my earlier
suggestion of using "and" as a separator for the iterators, since they
clearly should not be separated, but are indeed contained within each
other, so to speak.

(Or am I just confused here?)

--

  Magnus
  Lie
  Hetland



More information about the Python-list mailing list