On Wed, Oct 29, 2014 at 10:39 PM, Clayton Kirkwood <c...@godblessthe.us> wrote:
> When I run: > values = [ ('a', 1), ('b', 2), ('a', 5), ('c', 7)] > key = 'a' > pair=[] > You just created an empty list and called it "pair". > [pair for pair in values if key == pair[0]] > Two things to bear in mind here: - The stepper variable in a list comprehension lives in a distinct namespace. To the human reader, the list called "pair" outside the comprehension and the object called "pair" inside look identical - but Bad Things would happen if Python were as easily confused as humans, so it isn't. To Python, they are no more alike than two humans who happen to have the same first name. - As soon as the list comprehension stops executing - from the reader's perspective, as soon as you read past the rightmost square bracket - it, and its stepper variable, disappear. You didn't assign the list that the comprehension generated _to_ anything, so it evaporates. (Of course, nothing is really gone until it's garbage collected - but since you don't have any control over that, consider it gone.) print(pair) > > I get []. > As expected - it's the same empty list you started out with, and you didn't do anything to it. > > When I run: > values = [ ('a', 1), ('b', 2), ('a', 5), ('c', 7)] > key = 'a' > pair=[] > You're still not doing anything with that list... > x=[pair for pair in values if key == pair[0]] > This time, you ARE doing something with the list that the comprehension generates - you're naming it "x". > print(x) > And now you're printing it. > > I get [('a', 1), ('a', 5)] > Again, as expected. I can't help thinking that part of the difficulty here is that you're using object names that aren't meaningful to Python, but that seem to be meaningful to _you_. "pair" is just a name; it doesn't mean anything to Python. Neither do "key" or "values" - but they SEEM meaningful, and they're kinda close to actual Python keywords. This is a bad and dangerous practice! Try changing it up: > whatsits = [ ('a', 1), ('b', 2), ('a', 5), ('c', 7)] > thingy = 'a' > twofer=[] > x=[twofer for twofer in whatsits if thingy == twofer[0]] Obviously you needn't make your variable names as silly as that, but - for your own sake - don't make them official-sounding either.
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor