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 }
To create an array use the new keyword, followed by a space, then the type, and then the number of rows in square brackets followed by the number of columns in square brackets, like this new int[numRows][numCols] . The number of elements in a 2D array is the number of rows times the number of columns.
We can also create an empty array in python by list comprehension in which we will use for loop with range(). After writing the above code (create empty array Python), Ones you will print ” my_array ” then the output will appear as “ [ 0, 0, 0 ] ”.
In Python to declare a new 2-dimensional array we can easily use the combination of arange and reshape() method. The reshape() method is used to shape a numpy array without updating its data and arange() function is used to create a new array.
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.
@Cameron is correct in suggesting that you use NumPy to deal with arrays of numerical data. And for the second part of your question, ~Niklas B. is spot on with his suggestion to use defaultdict
.
What hasn't been covered is why [[None]*6]*6
behaves strangely.
The answer is that [None]*6
creates a list with six None
s in it (like you expect), but [list]*6
does not make six independent copies of list
- it makes six copies of a reference to the same list
.
Idiomatic Python has a section that may explain this better: "Other languages have variables - Python has names".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With