0
x=[[0]*2]*2 print(x) x[0][0]=1 print(x[0][0]+x[1][0])
What is correct output 1 or 2 ?
4 Antworten
+ 1
Why don't you just run this piece of code in Code Playground and see for yourself?
+ 1
Run the code first.
This should make it clear.
[ [ 1, 0 ], [ 1, 0 ] ]
[ 0 1 ] -> sub list at index
[0,0 0,1][1,0 1,1]-> sub list elements index
https://code.sololearn.com/cI8AV2WkEvUz/?ref=app
+ 1
Multiplication operator for list
list * n
concatenate n shallow copies of list
[[0]*2]*2 =>
[0]*2 = [0, 0]
- creates list of two numbers (0)
[[0, 0] * 2] = [[0, 0], [0, 0]]
- creates list of two shallow copies of the list [0,0]
this means that both element of [[0, 0], [0, 0]] refer to the same list=[0, 0].
x=[[0]*2]*2 = [ref, ref], where ref is a reference to [0,0] list
when you modify elements of x[0] the same changes will be visible as X[1] as they both refer to the same list.
x[0][0] = 1 changes list [0, 0] to [1, 0]
As both elements of x refer to that list
x will be [[1,0],[1,0]]
x[0][0]+x[1][0] = 1 + 1 = 2
0
It's 2 explain why?