Matteo Secco Matteo Secco - 15 days ago 6
Python Question

Appending the same list to another one

I have to append the same list to another one more than one time, and then modify only one of them.
I tried

list_a = []
list_b = [0,0,0]
for x in range(3):
list_a.append(list_b)


but the problem is that if I try

list_a[0][0] = 1


it modifies
list_a[1][0]
and
list_a[2][0]
also.
How can I avoid that?

Answer

Use the following:

list_a = []
list_b = [0,0,0]
for x in range(3):
    list_a.append(list_b[:])