0

I am trying to iterate through a list of lists of objects in using for loops. At the end of each iteration when I have isolated one object I am trying to call a method from that object. The problem is that each time I iterate through I am getting the a copy of the 2nd list acting in place of the 1st and 2nd list. I don't get it at all. Here is my code.

from sys import stdout

class Map:

    def show(self):
        for row in self.grid:
            print '' #\n
            for room in row:
                stdout.write(' ')#space
                room.show()

    def __init__(self, rooms):
        x_list, y_list = [],[]
        for room in rooms:
            x_list.append(room.loc[0])
            y_list.append(room.loc[1])
        great_x = max(x_list)
        great_y = max(y_list)
        self.grid = [[None] * (great_x+1)] * (great_y+1)
        for room in rooms:
            self.grid[room.loc[1]][room.loc[0]] = room

Room is a class that has attributes loc which is the x y location of the room in the form [x,y]. Room also has a method called show() which just prints out the string for that room.

The outcome of the above is: [Red] [Bro] [Red] [Bro]

it's supposed to be: [Bla] [Blu] [Red] [Bro]

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
Srok35
  • 3
  • 1

1 Answers1

1

This is creating many references to the same list

self.grid = [[None] * (great_x+1)] * (great_y+1)

You need to use a list comprehension like this

self.grid = [[None] * (great_x+1) for y in (great_y+1)]

This creates a new [None] * (great_x+1) for each y

John La Rooy
  • 295,403
  • 53
  • 369
  • 502