Python Forum

Full Version: How to create and define in one line a 2D list of class objects in Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am attempting to create a hex based strategy game, and I am using Pygame for the first time. Also, while I have many years of experience in coding, this is the first time I use classes and objects.

The Hex class needs to be defined with x and y, and when I try to create a MAP list made of hex objects, I do not know how to define in one line the instances:
Class Hex(): def __init__(self, x, y): self.x = x self.y = y hex_map = [[Hex(i,j) for j in range(1,10)] for i in range(1,10)]

Python generates an error because the variable i was not declared when Hex(i,j) is introduced... Is there a way to do it?
See commented corrected code below
class Hex: # should be lower cass class def __init__(self, x, y): # indent 4 spaces not 2 self.x = x # indent another 4 spaces inside of the def self.y = y # indent another 4 spaces inside of the def hex_map = [[Hex(i, j) for j in range(1, 10)] for i in range(1, 10)] # should not be indent here