Why did the values in array elements change?

Viewed 20

the list values of my code from a[ 0 ][ 0 ] to a[ 0 ][ 3 ] have changed but I'm not sure why...

Code:

inputBin = list(input("Enter a binary number (max. 8 bits): "))
a = [[0] * 4] * 2


for j in range(2):
    for i in range(4):
        a[j][i] = int(inputBin[(2 * j) ** 2 + i])
        print("a[", j,"][",i,"] = ", a[j][i])

for j in range(2):
    for i in range(4):
        print("a[",j,"][",i,"] = ",a[j][i])

Output

Enter a binary number (max. 8 bits): 11000011
a[ 0 ][ 0 ] =  1
a[ 0 ][ 1 ] =  1
a[ 0 ][ 2 ] =  0
a[ 0 ][ 3 ] =  0
a[ 1 ][ 0 ] =  0
a[ 1 ][ 1 ] =  0
a[ 1 ][ 2 ] =  1
a[ 1 ][ 3 ] =  1
a[ 0 ][ 0 ] =  0
a[ 0 ][ 1 ] =  0
a[ 0 ][ 2 ] =  1
a[ 0 ][ 3 ] =  1
a[ 1 ][ 0 ] =  0
a[ 1 ][ 1 ] =  0
a[ 1 ][ 2 ] =  1
a[ 1 ][ 3 ] =  1

Notice that a[ 0 ][ 0 ] to a[ 0 ][ 3 ] at the bottom are different from the top.

Output picture

1 Answers

the fallowing line a = [[0] * 4] * 2 will create 1 inner list with 2 references, you can use:

a = [[0] * 4 for _ in range(2)] 
Related