# [Python-Dev] zip() and list-comprehension with commas

Ka-Ping Yee ping@lfw.org
Wed, 12 Jul 2000 01:36:25 -0700 (PDT)

```On Wed, 12 Jul 2000, Peter Schneider-Kamp wrote:
> +1 on this. no performance hit (probably a small gain),
> "zip" is imho the right name (see e.g. haskell).

Indeed, a nice coincidence. :)

> --------------------------------------------------------------------
>
> I know special character are evil, but in this case I think
> [<expr> | <clause>, <clause>, ...]
> would be on order of magnitude easier to read. Why not?

Alas, the vertical bar is already a bitwise-or operator, and
couldn't safely be placed next to the <expr>.

Hmm.  How much of that "order of magnitude" comes from "|" looking
like the math notation, and how much from the mere fact that "|"
is distinguished from ","?

Semicolon might be worth considering here, actually: [f(x); for x in l]

> --------------------------------------------------------------------
>
> Would [x,y , for x in list1, if x > 1, if y > 2, for y in list2]
> be allowed? In other words: Should there be some rules of ordering?
> What would the above list comprehension produce for
> list1 = list2 = [1, 2, 3]?

I would say raise SyntaxError on this example.

Also, the way you've written the example would depend on an
existing variable named 'y' because you put "if y > 2" outside
of "for y in list2".  If the existing variable was <= 2, you'd
get an empty list.  For the following, i'm assuming you intended
to put "if y > 2" last.

As for the SyntaxError, i think it's a good idea because the
example could be ambiguous.  You would have to either say

[(x, y), for x in list1, if x > 1, for y in list2, if y > 2]

or

[x] + [y, for x in list1, if x > 1, for y in list2, if y > 2]

The first would produce [(2, 3), (3, 3)], and the second would
depend on the initial value of x and look like [x, 3, 3].

> --------------------------------------------------------------------
>
> Would the following be allowed (and desirable)?
> y = 3
> [ x + y , for x in [1, 2, 3], if x > 1]
> producing [5, 6]

Absolutely.

> --------------------------------------------------------------------
>
> I don't know Python's parser, so I am sorry if this is a non-issue:
> How does it resolve the ambiguity between
> [<expr>, <expr>, ...] and [<expr>, <clause>, <clause>, ...]?
> Especially something like
> [x, y, z, for x in l1, for y in l2, for z in l3] concerns me.

I guess it depends how the argument about parens-around-tuples
finally resolves, but personally i'd say that more than one expr
before an attempted iteration clause should cause a SyntaxError.

It would have to be written:

[(x, y, z), for x in l1, for y in l2, for z in l3]

-- ?!ng

```