0

I am writing code for concentric rectangle and initializing 'result' variable as,

[[0 for x in range(array_size)] for y in range(array_size)],

and I get the right answer. However, when I initialize 'result' variable as [[0]*array_size]*array_size, I get a wrong answer. The rest of my procedure is same for both the cases:

class Solution:
    def concentric(self, A):
        array_size = 2*A - 1
        result = [[0 for x in range(array_size)]
                 for y in range(array_size)];
                 #[[0]*array_size]*array_size
        
        for i in range(array_size):
            for j in range(array_size):
                if (abs(i-(array_size//2)) > abs(j-(array_size//2))):
                    result[i][j] = abs(i - array_size//2)+1;
                else:
                    result[i][j] = abs(j - array_size//2)+1;
        return result
Solution().concentric(3)

The output looks like this:

[[3, 3, 3, 3, 3], [3, 2, 2, 2, 3], [3, 2, 1, 2, 3], [3, 2, 2, 2, 3], [3, 3, 3, 3, 3]]

Any suggestion or explanation would be appreciated.

Qasim Ali
  • 1
  • 1
  • Does this answer your question? [List changes unexpectedly after assignment. Why is this and how can I prevent it?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it) – Tom McLean Jul 11 '21 at 06:26

2 Answers2

0

When you do this:

[[0]*array_size]*array_size

You are not creating a list of N different lists. Instead, you are creating a list with N references to the SAME list. If you modify any of them, you modify all of them. You can't initialize lists of lists using the * operator.

Usually, I find that it's better to create an empty list, and add the rows one by one as I create them.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

In the second initialisation, each row points to the same list. So when you are modifying elements in 1 row, effectively modifying that element in all rows. This can be validated by the following example. `

In [19]: a = [[0]*2]*2

In [20]: a
Out[20]: [[0, 0], [0, 0]]

In [21]: a[0] is a[1]
Out[21]: True

In [22]: a[1]
Out[22]: [0, 0]

In [23]: a[1][0]
Out[23]: 0

In [24]: a[1][0] = 1

In [25]: a[0] is a[1]
Out[25]: True

In [26]: a[0]
Out[26]: [1, 0]
Arun
  • 59
  • 7