Python Forum
Array initialization anomaly - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Array initialization anomaly (/thread-28205.html)



Array initialization anomaly - JohnPie - Jul-09-2020

Depending on how I initialize an array its behaviour is different and in one case seems like a Python bug. In my example I create two 3 X 10 arrays using different techniques. I then set elements of these arrays to a value and print them out with surprising results. Here is my code:
x=[[0]*4]*10 
y=[ [ 0 for i in range( 4 ) ] 
             for j in range( 10 ) ]
if x==y: print("same")
for i in range(10):
    x[i][0]=i
    y[i][0]=i
print(x)
print(y)
After running this code x and y should be the same but they are not. What am I doing wrong? Obviously, I will not use:
x=[[0]*4]*10 
in the future. Nevertheless it is perplexing.


Output:
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> = RESTART: C:\Users\John PC 2017\AppData\Local\Programs\Python\Python37\test.py same [[9, 0, 0, 0], [9, 0, 0, 0], [9, 0, 0, 0], [9, 0, 0, 0], [9, 0, 0, 0], [9, 0, 0, 0], [9, 0, 0, 0], [9, 0, 0, 0], [9, 0, 0, 0], [9, 0, 0, 0]] [[0, 0, 0, 0], [1, 0, 0, 0], [2, 0, 0, 0], [3, 0, 0, 0], [4, 0, 0, 0], [5, 0, 0, 0], [6, 0, 0, 0], [7, 0, 0, 0], [8, 0, 0, 0], [9, 0, 0, 0]] >>>



RE: Array initialization anomaly - deanhystad - Jul-09-2020

x=[[0]*4]*10 creates the array[0, 0, 0, 0] and then makes an array that holds ten of these arrays. All of the arrays inside x are the same array. Not the same values (which they are), but the same array. It is as if you did this:
y=[0]*4
x=[y,y,y,y,y,y,y,y,y,y]
A slightly shorter version of what you came up with:
x=[[0]*4 for _ in range(10)]
x[0][0] = 1
print(x)
Output:
[[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], ...