Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to construct an array of unique objects?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading