Comprehension List In Python2 Works Fine But I Get An Error In Python3
Solution 1:
Since x
y
and z
are defined as "local" variables in the list comprehension, Python 3 considers them as such, and doesn't use/see the global value.
Python 2 doesn't make that difference (hence the variable "leak" that some have observed when exiting a comprehension) and it behaves exactly like if you used normal loops
This is better explained here: Python list comprehension rebind names even after scope of comprehension. Is this right?
What is really funny is that python complains about y
first and not x
. Well, since I'm curious I've asked this question here: why the UnboundLocalError occurs on the second variable of the flat comprehension?
The proper way to do this is to use different variable names for your loop indices (not sure if the names I chose are very good, but at least this works regardless of the python version):
ret_list = [ (x1,y1,z1) for x1 in range(x+1) for y1 in range(y+1) for z1 in range(z+1) if x1+y1+z1!=n ]
Post a Comment for "Comprehension List In Python2 Works Fine But I Get An Error In Python3"