0

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?

julienc
  • 19,087
  • 17
  • 82
  • 82
  • 2
    `list_a.append(list_b[:])` -- append copies of `list_b` instead of the original – khelwood Nov 22 '16 at 19:58
  • Really thank you! @khelwood – Matteo Secco Nov 22 '16 at 20:00
  • "I have to append the same list to another one more than one time" - and now you have the *same list* appended to the other one several times, which is the problem. You need to make multiple lists instead of reusing the same one. – user2357112 Nov 22 '16 at 20:16

3 Answers3

1

Better way to create a list like this if all you want is to create empty list with all 0s is:

my_list = [[0]*3 for _ in range(3)]

Let's verify the result whether it has the same issue or not:

>>> my_list
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> my_list[0][0] = 1
>>> my_list
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
# ^          ^          ^
# Yipee! value changed only once

For knowing the reason why your code is not working, check: Python list of lists, changes reflected across sublists unexpectedly

Community
  • 1
  • 1
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

Use the following:

list_a = []
list_b = [0,0,0]
for x in range(3):
    list_a.append(list_b[:])
ettanany
  • 19,038
  • 9
  • 47
  • 63
0

You are appending list_b three times, so what you are modifying is the actual list_b object. What you want to do is to make a shallow copy, this be done like this

list_a.append(list(list_b))

or like this

list_a.append(list_b[:])
maagaard
  • 21
  • 4