On Fri, Aug 2, 2013 at 10:02 AM, Jim Mooney <[email protected]>wrote:
> On 2 August 2013 00:46, Alan Gauld <[email protected]> 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
_______________________________________________ Tutor maillist - [email protected] To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
