Jul-09-2020, 12:50 PM
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:
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:
in the future. Nevertheless it is perplexing.
1 2 3 4 5 6 7 8 9 |
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) |
1 |
x = [[ 0 ] * 4 ] * 10 |
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]]
>>>