I have a Python program that I want to create different lists in a for loop and then store these list in another list to create an array. I take one input list, modify it and append it to storage list, and then repeat. My problem is that when I update the next list in the loop all lists in the array also gets updated, so I end up with an array containing multiple identical lists.
array = []
road = [1,0,0,0,0,0,0,0]
array.append(road)
for i in range(0,len(road)-1):
if road[i] == 1:
road[i] = 0
road[i+1] = 1
print(road)
array.append(road)
The print(road) yields exactly what I want namely
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 0, 0, 0, 1]
but the array after the last iteration contains
[[0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1]]
and after the first iteration
[[0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0]]
What can I do to stop the array from updating when I'm changing the list in the for loop?
array.append(road)
Change this to
array.append(road[:])
to append a copy of the list. That way you have multiple different lists appended rather than the same list object appended repeatedly.
array.append(road)
Change this to
array.append(road[:])
to append a copy of the list. That way you have multiple different lists appended rather than the same list object appended repeatedly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With