[Tutor] implied tuple in a list comprehension

Hugo Arts hugo.yoshi at gmail.com
Fri Aug 2 10:27:19 CEST 2013


On Fri, Aug 2, 2013 at 10:02 AM, Jim Mooney <cybervigilante at gmail.com>wrote:

> On 2 August 2013 00:46, Alan Gauld <alan.gauld at btinternet.com> wrote:
> > On 02/08/13 08:32, Jim Mooney wrote:
>
> > How should Python interpret this?
> >
> > As
> >
> > x = [idx, (word for idx, word in S)]
> >
> > Or
> >
> >
> > x = [(idx, word) for idx, word in S]
> >
> > It's ambiguous.
> >
> I see what you mean, but I figured it can't be ambiguous if one
> interpretation makes no sense, and I can't see what   x = [idx, (word
> for idx, word in S)] could possibly mean. Am I assuming too much
> foresight on the part of the parser or does that actually mean
> something?
>
>
Yes, it means something very clear, try running it:

>>> s = zip(range(10), range(10, 0, -1))
>>> s
[(0, 10), (1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 2),
(9, 1)]
>>> idx = "hello"
>>> x = [idx, (word for idx, word in s)]
>>> x
['hello', <generator object <genexpr> at 0x7f54a21e0780>]
>>>

it means "make the name 'x' point to a list, with as its first element the
variable 'idx' and as its second variable a generator expression. The
generator expression takes s, assumes it is a sequence of 2-tuples (by
unpacking each item into two variables, 'idx' and 'word', and grabs the
second item ('word') from each tuple.

HTH,
Hugo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130802/2801e53c/attachment-0001.html>


More information about the Tutor mailing list