Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python deque scope?

Tags:

python

list

deque

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])
like image 551
Sjieke Avatar asked Jan 07 '13 03:01

Sjieke


People also ask

Is deque iterable python?

Unlike some other collections, a deque is fully iterable. This means that you can obtain a list of items by using a for loop whenever necessary.

Is deque better than list python?

For lists, it's always O(1). So, for accessing elements, lists are always a better choice, it's not at all what deques were designed for. Second, because deques are implemented as doubly-ended arrays, they have the advantage when appending or popping from both the right and the left side of a deque (measured as O(1)).

What does deque () do in python?

A double-ended queue, or deque, has the feature of adding and removing elements from either end. The Deque module is a part of collections library. It has the methods for adding and removing elements which can be invoked directly with arguments.

Can we slice a deque in python?

Second, why isn't list slicing notation of any kind allowed on a python deque? There are just no types in the standard library where this makes sense. The deque type is a linked list and indexing past 0 and -1 is inefficient (read, takes O(N) time), so slicing those doesn't make much sense.


1 Answers

You are putting an object in the deque, then changing the object. In fact, you always put the same object into the deque, so all the deque has are references to one object p.

like image 180
Ned Batchelder Avatar answered Sep 20 '22 12:09

Ned Batchelder