Python code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python code

Why is this code giving output [[1,0],[1,0]] instead of [[1,0],[0,0]] x = [[0]*2]*2 x[0][0]= 1 print(x)

2nd Dec 2021, 5:28 PM
Gajendra Sonare
Gajendra Sonare - avatar
4 Answers
+ 7
List of lists, so your dealing with list references so change in one list changes in the same reference list. Gajendra Sonare x = [0]*2 y = [x]*2 #equals to [x,x] x[0]= 1 # all x refferences will effect x=[1, 0] print(y) # [x,x]
2nd Dec 2021, 6:36 PM
Jayakrishna 🇮🇳
+ 2
Your code is equivalent to this: x = [[0,0]] x = x + x x[0][0] = 1 print(x) I hope this makes it easier to understand what's going on ☺️
3rd Dec 2021, 1:20 AM
Solo
Solo - avatar
0
Let’s break it up step by step: 1) [[0]*2] is equal to [0, 0] 2) [0, 0] * 2 is equal to [[0, 0], [0, 0]] 3) Now regard your second line as (x[0])[0] which means the first index of the first list item: ([0, 0])[0]. Then you are replacing the first 0 with 1: [[0, 0], [0, 0]] becomes [[1, 0], [0, 0]] What if you try these instead of x[0][0] = 1: for item in x: item[0] = 1 print(x) The whole code would be: x = [[0]*2]*2 for item in x: item[0] = 1 print(x)
3rd Dec 2021, 4:13 PM
Pouria Hosseini
Pouria Hosseini - avatar