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]*10in the future. Nevertheless it is perplexing.
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)
|