+ 2

Python Quiz Question Help

Could anyone explain why the following code x = [[0] * 2] * 2 x[0][0] = 1 print(x) returns [[1,0],[1,0]] and not [[1,0],[0,0]] How does x[0][0] impact both?

11th Mar 2018, 12:57 AM
Raithen
Raithen - avatar
1 Answer
+ 3
In python lists are referenced type. It means that values are kept on heap and stack keep reference to this values. In your case when we multiply list it copies the reference and now we have two lists that refers to the same value, so when you change one of them it affects both.
11th Mar 2018, 1:39 AM
Vladi Petrov
Vladi Petrov - avatar