I'm really stuck at a problem, where I completely don't understand why the output is what it is and not what I expected. I basically want to calculate values for the elements of a nested list which is initialized with only zeros. Here is the code of a simple form of my problem:
aa = [[0] * 2] * 2
for i in range(2):
for j in range(2):
for k in range(0, 10):
aa[i][j] += k
I expected here the output for "aa" to be: [[45, 45], [45, 45]].
But the output is: [[90, 90], [90, 90]]
How can that be? Any explanation would be helpful. After debugging I saw that Python adds the k always to both lists in the list, although i is for example currently 0.
That is because the shallow copy of list. aa = [[0] * 2] * 2
creates shallow copy, try aa = [[0]*2 for i in range(2)]
aa = [[0]*2]*2
print(aa[0]) #[0,0]
print(aa[1]) # [0,0]
aa[0][0] = 2
aa[0][1] = 2
print(aa[0]) #[2,2]
print(aa[1]) # [2,2] !!
# +-------+-------+
# | aa[0] | aa[1] |
# +-------+-------+
# | |
# | |
# \ /
# [0 , 0]
# Both referring to the same list
# So whatever operation you do in aa[0] will reflect in aa[1] and vice versa
# Because effectively they are pointing to same list
# id(aa[0]) == id(aa[1]) ---> True
aa = [[0]*2 for i in range(2)]
for i in range(2):
for j in range(2):
for k in range(0, 10):
aa[i][j] += k
[[45, 45], [45, 45]]