I have a problem with initialzing a 2D array in python. I want a 6x6 array, I did
arr = [[None]*6]*6
But when I do:
>>> arr[1][2]=10
>>> arr
[[None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, None, None, None], [None, None, 10, None, None, None]]
Notice I just set 1 item, and its "replicated" on all rows. Whats wrong? I think it has to do with its referencing the same list, but how do I fix this?
I figured
for key, _ in algos.items():
algoData[key] = []
for i in range(0,6):
algoData[key].append([])
for j in range(0,6):
algoData[key][i].append(None)
works, but it seems long to just initialize an empty 6x6 array, what if I want a 10000x10000 array, it will be very inefficient?
UPDATE
Can I also initialize a dictionary of 2D arrays? I have a dictionary like:
algos = { "FIFO": ..., "LRU": ..., "Random": ... }
I want to initialize a dictionary like below:
algoData = { "FIFO": 2D arr, "LRU": 2D arr, "Random": 2D arr }
See Question&Answers more detail:
os