Within my code I need to create an array of a user specified magnitude, usually the code I’d use for this is:
array = [[x] * a for b in range(size)]
In the above examples the variables are as follows:
x -> item in the array spaces
a -> width
b -> height
However I used this code to try and make the array house objects as follows:
gameboard = [[Cell(screen_size, size)] * size for size in range(size)]
In this case x is my object "Cell" with the variables that need to be passed in for it, and a / b are both size, as the array is to be square. The issue I’m facing is the top row, forms correctly where new objects are created, however, the following rows are just repeats of the top row, not new objects as they should be.
For Example if size was 5, I want a 5×5 of 25 different cell objects, however instead I get a 5×5 where the top layer is unique objects however the rest are only copies, therefore I have 5 unique objects with 5 references each rather than 25 unique objects.
Any help would be appreciated.
>Solution :
You have to explicitly call the instructor to create new objects of a certain class. The expression [Cell(screen_size, size)] * size does not do this, it creates a copy of the list [Cell(screen_size, size)] size times.
A fix could be a nested list comprehension statement:
gameboard = [[Cell(screen_size, size) for _ in range(size)] for size in range(size)]
This not only calls the Cell constructor for each row, but for each element in the row as well.