Search code examples
pythonlistdeque

Python deque scope?


I am learning Python and have been trying to make a deque. However, I get incorrect output and I am not sure why. My code is as follows:

p = [2, 1], [1, 1]
init_q= deque()

init_q.append(p)
for i in range(len(p)):
    for j in range(len(p[i])):
        temp = p[i][j]
        p[i][j] = 0
        init_q.append(p)
        p[i][j] = temp

while init_q:
    print init_q.pop()

In this code I take in a list, I then want to create a queue with 5 list, 4 of which have a 0 in them at different locations, the result I want is:

([2, 1], [1, 1])
([0, 1], [1, 1])
([2, 0], [1, 1])
([2, 1], [0, 1])
([2, 1], [1, 0])

However, the result I get is:

([2, 1], [1, 1])
([2, 1], [1, 1])
([2, 1], [1, 1])
([2, 1], [1, 1])
([2, 1], [1, 1])

Solution

  • I created a visualization on Python Tutor by simplifying your code. Fiddle around and you can easily see what's happening.

    A single line change to your code can fix this.

    init_q.append(map(list, p))    # Initialize a new list from p's element lists
    

    Here's the visualization by using the above change.