Search code examples
pythondeque

Why does a deque constructed from a single list return its item rather than the list itself?


I run the code below:

from collections import deque
q = deque([('0000',0)])
a = q.popleft()

print(a)
print(type(a))

b = [('0000',0)]

print(b)
print(type(b))

And output is:

('0000', 0)
<class 'tuple'>
[('0000', 0)]
<class 'list'>

I wonder why type of a is tuple, but b is list. I expected q.popleft() to return [('0000', 0)].


Solution

  • deque aceepts an iterable as its argument. It then unpacks that iterable to get the elements to fill the deque.

    ie, if you pass

    [1, 2, 3]
    

    to deque as

    q = deque([1, 2, 3])
    

    the deque will have 1, 2 and 3 as its elements. Not [1, 2, 3]

    (it follows that, you cannot initialize a deque with multiple arguments to be used as its elements.)

    If you think of deque as only a list,

    deque([1,2,3]) is equivalent to the list [1,2,3], not [[1, 2, 3]]. For it be equivalent to [[1, 2, 3]], you would have to call deque([[1,2,3]])