Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid updating nested lists in for loop

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?

like image 858
Djamillah Avatar asked Dec 06 '25 10:12

Djamillah


2 Answers

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.

like image 77
John Kugelman Avatar answered Dec 07 '25 23:12

John Kugelman


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.

like image 22
John Kugelman Avatar answered Dec 08 '25 01:12

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!