0

Here is a snippet of python code:

a = [[0]*3]*4
for i in range(4):
    for j in range(3):
        a[i][j] = i+j
        print(a[i][j])
print(a)

However, the outputs of the two prints are different.

The former one prints what I want. And the second prints all the same for the 4 sublists.

It seems the problem of shallow copying. I really don't understand how and why it happens.

Update:

After I have solved this, I found another problem:

a = [[0]*3]*4
for i in range(4):
    a[i] = [i, 2*i, 3*i]

The result is also what I want. I'm once again confused about this.

Who can tell me the difference?

haik
  • 43
  • 3

2 Answers2

-1
a = [[0]*3]*4
for i in range(4):
    for j in range(3):
        a[i][j] = i+j
        print(a)
        print(a[i][j])//show the execution at every step
print(a)

At each step the list with same column is updated with the same value. output is

[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
0
[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
1
[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]
2
[[1, 1, 2], [1, 1, 2], [1, 1, 2], [1, 1, 2]]
1
[[1, 2, 2], [1, 2, 2], [1, 2, 2], [1, 2, 2]]
2
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
3
[[2, 2, 3], [2, 2, 3], [2, 2, 3], [2, 2, 3]]
2
[[2, 3, 3], [2, 3, 3], [2, 3, 3], [2, 3, 3]]
3
[[2, 3, 4], [2, 3, 4], [2, 3, 4], [2, 3, 4]]
4
[[3, 3, 4], [3, 3, 4], [3, 3, 4], [3, 3, 4]]
3
[[3, 4, 4], [3, 4, 4], [3, 4, 4], [3, 4, 4]]
4
[[3, 4, 5], [3, 4, 5], [3, 4, 5], [3, 4, 5]]
5
[[3, 4, 5], [3, 4, 5], [3, 4, 5], [3, 4, 5]]
Amar
  • 16
  • 2
  • 1
    The reason is that "* 4" just makes 3 references to the existing sublist [[0]*3] instead of making new sublists. Therefore, essentially it only creates only 1 sublist here. – haik May 20 '18 at 05:23
-3

The multiplier of operator taking a list and an int will make makes shallow copies of the elements of the list, so you're on the right track.

Initialise like this instead

a = [[0] * 3 for _ in range(4)]
vidstige
  • 12,492
  • 9
  • 66
  • 110
  • Thanks. I have figured out why it happens from a previous question. Your answer is right, however, I don't know why the displayed post score is minus. – haik May 20 '18 at 05:09