Python Forum
Array initialization anomaly
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Array initialization anomaly
#1
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]] >>>
Reply
#2
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], ...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  SystemError: initialization of integer failed without raising an exception Anldra12 2 4,394 Apr-19-2022, 10:50 AM
Last Post: Anldra12
  A dynamic link library (DLL) initialization routine failed ish93 0 1,786 Jan-11-2021, 08:22 PM
Last Post: ish93
  Matrix indexing and initialization in " for in" loop QuintenR 2 1,865 Dec-23-2020, 05:59 PM
Last Post: QuintenR

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020