BUG? list-comprehension's inconsistency? was: Re: list-display semantics?
Bengt Richter
bokr at accessone.com
Sun Jun 10 19:19:27 EDT 2001
On Sun, 10 Jun 2001 23:00:30 +0400 (MSD), Roman Suzi <rnd at onego.ru>
wrote:
>On Mon, 11 Jun 2001, jainweiwu wrote:
>
>BTW, I think it could be list-comprehension's
>inconsistency (if not a bug!), look:
>
>1->>> [x for x in [1, 2, 3], y for y in [4, 5, 6]] # first try
>Traceback (most recent call last):
> File "<stdin>", line 1, in ?
>NameError: name 'y' is not defined
>2->>> [x for x in [1, 2, 3], [y for y in [4, 5, 6]]]
>[[1, 2, 3], [4, 5, 6]]
>3->>> [[x for x in [1, 2, 3]], [y for y in [4, 5, 6]]]
>[[1, 2, 3], [4, 5, 6]]
>4->>> [x for x in [1, 2, 3], y for y in [4, 5, 6]] # 2nd try
>[[1, 2, 3], [1, 2, 3], [1, 2, 3], 6, 6, 6]
>
>-- and this lead to subtle errors.
It is subtle, but not a bug per se, if you ask me.
But it is like a combination of operator precedence and
name scope traps for the unwary, which I was ;-)
>
>There are even two things which seem wrong here:
>
>A) 1 and 4-s steps differ only because y is now defined.
>B) results of step 2 and 3 do not differ, while visually
>I've added [] around first item.
I think it's the implicit tuplification again, but so long
as that's legal we can't complain that 2+3 and 4+1 have the
same result, even though the expressions look different ;-)
>2->>> [x for x in [1, 2, 3], [y for y in [4, 5, 6]]]
Tuplifying:
>>> [x for x in ( [1, 2, 3], [y for y in [4, 5, 6]] )]
[[1, 2, 3], [4, 5, 6]]
or:
>>> xtuple = ( [1, 2, 3], [y for y in [4, 5, 6]] )
>>> xtuple
([1, 2, 3], [4, 5, 6])
>>> [x for x in xtuple ]
[[1, 2, 3], [4, 5, 6]]
>3->>> [[x for x in [1, 2, 3]], [y for y in [4, 5, 6]]]
ISTM this one has to be legal, since it's just a list of
expressions which individually happen to be (unambiguous)
list comprehensions.
I.e.,
>>> xcomp = [x for x in [1, 2, 3]]
>>> ycomp = [y for y in [4, 5, 6]]
>>> [[x for x in [1, 2, 3]], [y for y in [4, 5, 6]]]
[[1, 2, 3], [4, 5, 6]]
>>> [ xcomp, ycomp ]
[[1, 2, 3], [4, 5, 6]]
I hope I am not misleading anyone. I am still new to Python.
More information about the Python-list
mailing list