Python Forum
variable not defined inside a list comprehension
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
variable not defined inside a list comprehension
#1
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
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  function defined inside a function Skaperen 2 2,414 May-13-2021, 01:04 AM
Last Post: Skaperen
  what's homogeneus items defined by list frank0903 5 2,388 Jun-25-2020, 11:26 AM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020