0

Thank you for supporting Python learners, who got stuck! I'd like to create an array of objects and encountered some weird behaviour of Python. Here's the code:

class Box:
    def __init__(self, row, col):
        self.row = row
        self.col = col
    def __str__(self):
        return f"this is box[{self.row}][{self.col}]"

# instancing the boxes
boxes = 3*[3*[None]]

for i in range(2):
    for j in range(2):
        boxes[i][j] = Box(i, j)
        print(boxes[i][j])
print()
print(boxes[0][0])

And this is the output:

this is box[0][0]
this is box[0][1]
this is box[1][0]
this is box[1][1]

this is box[1][0]

The last print statement shows the problem: When you call boxes[0][0], you get boxes[1][0]. Python seem to stick with the last instanced row index. This problem does not occur with list of objects, only with arrays. I suspect a limitation in Python (I'm using 3.8.5). I searched the web, but found nothing. What do you think is the problem here? How would you create this array of objects? Thank you very much for your help!

Kirsten
  • 1
  • 1
  • "This problem does not occur with list of objects, only with arrays." - these are still lists. "Array" in Python typically refers to one of several other data types, usually NumPy arrays, but also sometimes `array.array` arrays or ctypes arrays. – user2357112 Oct 11 '20 at 19:59
  • Thank you for your comment. The solution of my problem is: – Kirsten Oct 11 '20 at 20:30
  • boxes = [2*[None] for _ in range(2)] – Kirsten Oct 11 '20 at 20:30

0 Answers0