list-display semantics?

Tim Peters tim.one at home.com
Sun Jun 10 15:45:24 EDT 2001


[jainweiwu]
> I tried the one-line command in a interaction mode:
>
> [x for x in [1, 2, 3], y for y in [4, 5, 6]]
>
> and the result surprised me, that is:
>
> [[1,2,3],[1,2,3],[1,2,3],9,9,9]
>
> Who can explain the behavior?
>
> Since I expected the result should be:
>
> [[1,4],[1,5],[1,6],[2,4],...]

It's "a feature", but a bad one, and I opened a bug report on it:

<http://sf.net/tracker/index.php?func=detail&aid=431886&group_id=5470&
atid=105470>

The problem is that your original got parsed as:

    [x for x in ([1, 2, 3], y) for y in [4, 5, 6]]
                ^            ^

which is roughly equivalent to:

    temp = []
    for x in ([1, 2, 3], y):
        for y in [4, 5, 6]:
            temp.append(x)

That interpretation of the comma is surprising in context, and I expect
Python will change to disallow it.  To get the effect you want:

>>> [[x, y] for x in [1, 2, 3] for y in [4, 5, 6]]
[[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6]]
>>>





More information about the Python-list mailing list