list-display semantics?

Remco Gerlich scarblac at pino.selwerd.nl
Sun Jun 10 17:24:57 EDT 2001


jainweiwu <parywu at seed.net.tw> wrote in comp.lang.python:
> Hi all:
> I tried the one-line command in a interaction mode:
> [x for x in [1, 2, 3], y for y in [4, 5, 6]]
                       ^

This is not the way to do what you want anyway, but it's the comma that
gives the strange result; "[1, 2, 3], y" is a tuple of two elements.

> and the result surprised me, that is:
> [[1,2,3],[1,2,3],[1,2,3],9,9,9]
> Who can explain the behavior?

What you wrote there means:
[x for x in ([1, 2, 3], y) for y in [4, 5, 6]]

So first x is [1, 2, 3], and it prints that for y=4, 5, 6 (the value of y
doesn't have any effect, so it just prints [1, 2, 3] three times). Then x
becomes y; and I *think* y was 9 before you wrote the list comprehension, so
it wrote that. That's the only explanation I can think of there.

> Since I expected the result should be:
> [[1,4],[1,5],[1,6],[2,4],...]

You write that like this:

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

-- 
Remco Gerlich



More information about the Python-list mailing list