Initializing shallow 2D arrays in Python

"Wild life: Heron In Shallow Water shot#2" by Jangra Works is licensed under CC BY 2.0


You may have seen that there is an easy way to initiate an array or 2D array with default values by multiplying the array with number of elements. 

row, col = 2,3
array = [[0] * col] * row
print (array)

[
[0, 0, 0],
[0, 0, 0]
]

This list is created as shallow list, which means outer array is pointing to the same inner arrays. When you change any value in the inner array, it will be visible to all outer arrays. Here is a good visual representation (ref).



When you make a change on any element of the inner array, it will make a change to all out array values as well because they are referencing to the same inner array (columns). 

array[0][1] = 1
print (array)

[
[0, 1, 0],
[0, 1, 0]
]


In order to make a independent 2D elements, you may use the list comprehension with inner and outer array. This subtle difference can be difficult to debug sometimes; therefore, I don't use shallow copy for my new arrays most of the time.

array = [[0 for i in range(col)] for j in range(row)]
array[0][1] = 1
print (array)

[
[0, 1, 0],
[0, 0, 0]
]

Comments

Popular posts from this blog

Space Character Problem on IE 6, 7, and 8

Does Netflix work on iOS 5 Beta 4?

AWS encryption chart (SSE-S3 vs SSE-KMS vs SSE-C)