![]() |
how do i get y to be recognized in this comprehension? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: how do i get y to be recognized in this comprehension? (/thread-20670.html) |
how do i get y to be recognized in this comprehension? - Skaperen - Aug-24-2019 how do i get y to be recognized in this comprehension?
RE: how do i get y to be recognized in this comprehension? - metulburr - Aug-25-2019 i think you mean this. >>> [x for y in ['foo','bar'] for x in [y.lower(),y.upper()]] ['foo', 'FOO', 'bar', 'BAR']The first for loop is the outer most loop. The way you have it written it is in the inner loop, but the upper method is in the outer loop causing a name error. RE: how do i get y to be recognized in this comprehension? - Skaperen - Aug-25-2019 my thinking was that in a comprehension, the "for" followed what it controlled. but it guess not. but wait, it does follow. now i'm even more confused. RE: how do i get y to be recognized in this comprehension? - ThomasL - Aug-25-2019 I can recommend this talk by Trey Hunner starting at around 48:00 or watch it from the beginning. RE: how do i get y to be recognized in this comprehension? - metulburr - Aug-25-2019 They follow suit with line after line in an expanded for loop except for what is controlled. This is that list comp expanded. Every line follows the previous line except x which goes first. for y in ['foo','bar']: for x in [y.lower(),y.upper()]: xmove second line to first line "after" for y in ['foo','bar']:for x in [y.lower(),y.upper()]: xremove colons for y in ['foo','bar'] for x in [y.lower(),y.upper()] xmove x first x for y in ['foo','bar'] for x in [y.lower(),y.upper()]enclose the entire thing in brackets [x for y in ['foo','bar'] for x in [y.lower(),y.upper()]]more info including if conditions mixed in with it here RE: how do i get y to be recognized in this comprehension? - Skaperen - Aug-26-2019 my thought process was that since the for followed the body, the outer for would follow what it applied to. instead, all the fors go together in regular order and the whole group follows what it all applies to. |