Python Forum
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?

Output:
Python 3.6.8 (default, Jan 14 2019, 11:02:34) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux Type "help", "copyright", "credits" or "license" for more information. >>> [x for x in [y.lower(),y.upper()] for y in ['foo','bar']] Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'y' is not defined >>>



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()]:
        x
move second line to first line "after"
for y in ['foo','bar']:for x in [y.lower(),y.upper()]:
        x
remove colons
for y in ['foo','bar'] for x in [y.lower(),y.upper()]
    x
move 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.