pythonlist

Initializing 2D list in Python


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 }

Solution

  • Using list comprehensions, you can say:

    arr = [[None for x in range(6)] for y in range(6)]
    

    Then you will have arr[1][2] = 10 working as expected. This is not a very normal thing to do, however. What are you going to use the nested lists for? There may be a better way. For example, working with arrays is made much easier with the numpy package.