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 ?

20th Mar 2020, 11:14 AM
Programmer
Programmer - avatar
4 odpowiedzi
+ 1
Why don't you just run this piece of code in Code Playground and see for yourself?
20th Mar 2020, 11:51 AM
HonFu
HonFu - avatar
+ 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
20th Mar 2020, 12:34 PM
Avinesh
Avinesh - avatar
+ 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
20th Mar 2020, 1:07 PM
andriy kan
andriy kan - avatar
0
It's 2 explain why?
20th Mar 2020, 11:53 AM
Programmer
Programmer - avatar