Python Forum
How to create and define in one line a 2D list of class objects in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to create and define in one line a 2D list of class objects in Python
#1
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?
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to get qualified objects in a list Azdaghost 5 462 Apr-22-2025, 06:03 PM
Last Post: Azdaghost
  Create a new subclass in a Python extension based on an existing class voidtrance 6 1,413 Mar-25-2025, 06:37 PM
Last Post: voidtrance
  Entry field random pull from list, each return own line Bear1981 6 814 Feb-25-2025, 06:09 AM
Last Post: Pedroski55
  How does this code create a class? Pedroski55 6 2,061 Apr-21-2024, 06:15 AM
Last Post: Gribouillis
  How to read module/class from list of strings? popular_dog 1 1,338 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  How can I access objects or widgets from one class in another class? Konstantin23 3 2,635 Aug-05-2023, 08:13 PM
Last Post: Konstantin23
  Delete strings from a list to create a new only number list Dvdscot 8 3,366 May-01-2023, 09:06 PM
Last Post: deanhystad
  Create Excel Line Chart Programmatically dee 3 2,013 Dec-30-2022, 08:44 PM
Last Post: dee
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 2,855 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  Creating list of lists, with objects from lists sgrinderud 7 3,098 Oct-01-2022, 07:15 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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