0

I have the following minimal code that creates a nested list of dummy objects called numbers:

class number(object):
    def __init__(self, i):
        super(number, self).__init__()  # constructs the object instance
        self.num = i

    def show(self):
        return self.num

list_of_numbers = [[None] * 2] * 2

for i in range(2):
    for j in range(2):
        list_of_numbers[i][j] = number(i*j)
        print(list_of_numbers[i][j].show())

for i in range(2):
    for j in range(2):
        print(list_of_numbers[i][j].show())

What I find really confusing is that the above for loops, which display the content of the nested list, don't print the same result. The first loop prints the sequence '0001', as expected. The second prints '0101'.

If I then execute

print(list_of_numbers)

I get

[[<__main__.number object at 0x1226c35d0>, <__main__.number object at 0x1226a6050>], [<__main__.number object at 0x1226c35d0>, <__main__.number object at 0x1226a6050>]]

In other words, the nested list is pointing at two distinct objects in memory as opposed to four.

I also tried to initialise the list using deepcopy as follows:

list_of_numbers[i][j] = copy.deepcopy(number(i*j))

But that didn't change the result.

I'd like to find a way to initialise my nested list so that each of its components points to a different object instance.

Lance
  • 115
  • 1
  • 6

0 Answers0