Python Forum

Full Version: variable not defined inside a list comprehension
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, in a program i have a class like this one but when in run the code i get that x is not defined, is this problem relative to list comprehension?
class MyClass:
    x = 8
    y = 9
    grid = [[0 for _ in range(x)] for _ in range(y)]
Error:
Traceback (most recent call last): File "<input>", line 1, in <module> File "<input>", line 4, in MyClass File "<input>", line 4, in <listcomp> NameError: name 'x' is not defined
list comprehensions have their own scope, and they can only access variables defined within their own scope or in the outer scope.
In this case, x and y are defined as class variables,so they are not directly accessible within the list comprehension.
To fix this issue can make instance variables instead of class variables.
class MyClass:
    def __init__(self, x=8, y=9):
        self.x = x
        self.y = y
        self.grid = [[0 for _ in range(self.x)] for _ in range(self.y)]

my_instance = MyClass(3, 4)
print(my_instance.grid)
Output:
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
If call it like MyClass() it will make default 8, 9 grid.