I just read the answer to this question: Accessing class variables from a list comprehension in the class definition
It helps me to understand why the following code results in NameError: name 'x' is not defined
:
class A:
x = 1
data = [0, 1, 2, 3]
new_data = [i + x for i in data]
print(new_data)
The NameError
occurs because x
is not defined in the special scope for list comprehension. But I am unable to understand why the following code works without any error.
class A:
x = 1
data = [0, 1, 2, 3]
new_data = [i for i in data]
print(new_data)
I get the output [0, 1, 2, 3]
. But I was expecting this error: NameError: name 'data' is not defined
because I was expecting just like in the previous example the name x
is not defined in the list comprehension's scope, similarly, the name data
would not be defined too in the list comprehension's scope.
Could you please help me to understand why x
is not defined in the list comprehension's scope but data
is?