Codementor Events

Why it is working the way it is working?

Published Mar 17, 2020

Recently someone on LinkedIn shared a code snippet. And, asked. This is what is happening to the code and I am unable to figure out why. The problem wasn't explicitly stated.
0 (1).jpeg

Going through the code I understood what he was confused with.

Let us sneak peak into the code line by line.

a = [[0]*3]*3
a
Output - [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
a[0][0] = 1
Now, the output he was expecting was [[1, 0, 0], [0, 0, 0], [0, 0, 0]].
The actual output was [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

Wondering why?

Try doing id(a[0]), id(a[1]), id(a[2]) you would see that copies of the same list are being created by [[0]*3]*3. Hence each list points to the same memory address.

Hence, you would observe memory address(id in python) of a[0][0], a[1][0], a[2][0] is same. Therefore, all the corresponding values have got changed. 😃

Discover and read more posts from Mridu Bhatnagar
get started
post commentsBe the first to share your opinion
Show more replies