1

When I initialize a 2-dimensional matrix in the following way, the behavior is very strange to me.

In [1]: matrix = [[None] * 2] * 3                                               

In [2]: matrix                                                                  
Out[2]: [[None, None], [None, None], [None, None]]

In [3]: matrix[0][0] = 5                                                        

In [4]: matrix                                                                  
Out[4]: [[5, None], [5, None], [5, None]]

I now know I should initialize it in the following way to avoid this strange behavior:

matrix = [[None for x in range(2)] for x in range(3)]

Can someone explain why in the former case I am getting values duplicated across multiple arrays and is there benefit to this behavior?

Sean Chon
  • 397
  • 5
  • 13

1 Answers1

0

It's because the values are all the same object, same id, so you need to do:

matrix = [[None] * 2 for i in range(3)]

One range can be enough, the ids would be different now.

The reason why it is not working:

matrix variable is containing three identical items, totally the same, not only values are the same, same id, when you use range, they gonna be processed one by one, not altogether, and so the ids would be different, but values still same, so not all are the same, the stuff mentioned is causing really your problem, * isn't always the best, range is.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114