0

So I created a list within a list and printed it:

a = []
b = []
for i in range(3):
    a.append(0)
for i in range(3):
    b.append(a)
print(b)

and the result was: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] as expected

but when I try assigning the first value of the first list within b with

b[0][0] = 1
print(b)

the result comes out as: [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

How do I assign 1 to only the first value so I get: [[1, 0, 0], [0, 0, 0], [0, 0, 0]]?

adder
  • 3,512
  • 1
  • 16
  • 28

2 Answers2

2

You have three references to the same list (a) in b. Instead, create three lists. Easiest way is to make a copy of a when building b:

for i in range(3):
    b.append(a[:])
kindall
  • 178,883
  • 35
  • 278
  • 309
0

You have three of the same list in b. You could remove this dependency by:

b = []
for i in range(3):
    b.append([0]*3)   
print b