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


Messages In This Thread
Array initialization anomaly - by JohnPie - Jul-09-2020, 12:50 PM
RE: Array initialization anomaly - by deanhystad - Jul-09-2020, 01:48 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  SystemError: initialization of integer failed without raising an exception Anldra12 2 4,624 Apr-19-2022, 10:50 AM
Last Post: Anldra12
  A dynamic link library (DLL) initialization routine failed ish93 0 1,887 Jan-11-2021, 08:22 PM
Last Post: ish93
  Matrix indexing and initialization in " for in" loop QuintenR 2 1,970 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