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
#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


Messages In This Thread
RE: variable not defined inside a list comprehension - by snippsat - May-13-2023, 09:05 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  function defined inside a function Skaperen 2 2,456 May-13-2021, 01:04 AM
Last Post: Skaperen
  what's homogeneus items defined by list frank0903 5 2,417 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