"Martin A. Brown" <mar...@linux-ip.net> Wrote in message: > > Hi there Clayton, > >> values = [ ('a', 1), ('b', 2), ('a', 5), ('c', 7)] >> key = 'a' >> pair=[] # -- this assignment is unnecessary >> x=[pair for pair in values if key == pair[0]] >> print(x) >> >> I get [('a', 1), ('a', 5)] > > I also get that result. Good. > >> So, what does that first pair do? I see and have used the first >> comprehension. > > I'll point out that somebody (Cameron Simpson, specifically) already > gave you a hint that might have helped, but maybe you missed it as > you were trying to understand list comprehensions. > > Let's play a little game....I'm going to assume that the variables > values and key are initialized as you have initialized them above. > > > Game #1: Recognize that the name of the variable in the list > comprehension is ephemeral. > > >>> [frobnitz for frobnitz in values if key == frobnitz[0]] > [('a', 1), ('a', 5)] > > Yes, I guess that's obvious now. So, this is why people often use > 'x' in these situations. > > >>> [x for x in values if key == x[0]] > [('a', 1), ('a', 5)] > > The variable will probably contain the final element of the input > sequence after the list comprehension terminates.
NO, NO, NO. The OP is using Python 3.4, and has consistently shown results accordingly. x does NOT exist after the list comprehension. That was a flaw in python 2.x which has been fixed. -- DaveA _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor