In [1]:
import collections
d = collections.deque('abcdefg')
print('Deque', d)
print('length', len(d))
print('Left end:', d[0])
print('Right end:', d[-1])


Deque deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
length 7
Left end: a
Right end: g

In [3]:
d.remove('c')

In [6]:
print('remove(c)', d)


remove(c) deque(['a', 'b', 'd', 'e', 'f', 'g'])

Populating


In [7]:
import collections
d1 = collections.deque()
d1.extend('abcdefg')
print('extend', d1)
d1.append('h')
print('append', d1)


extend deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
append deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])

In [8]:
d2 = collections.deque()
d2.extendleft(range(6))
print('extend left', d2)
d2.appendleft(6)
print('append left', d2)


extend left deque([5, 4, 3, 2, 1, 0])
append left deque([6, 5, 4, 3, 2, 1, 0])

Consuming


In [9]:
import collections
print('From the right')
d = collections.deque('abcdef')
while True:
    try:
        print(d.pop(), end=' ')
    except IndexError:
        break
print()
print('\n From the left:')
d = collections.deque(range(6))
while True:
    try:
        print(d.popleft(), end=' ')
    except IndexError:
        break


From the right
f e d c b a 

 From the left:
0 1 2 3 4 5 

the deque is thread safe


In [10]:
import collections
import threading
import time

candle = collections.deque(range(5))
def burn(direction, nextSource):
    while True:
        try:
            next = nextSource()
        except IndexError:
            break
        else:
            print('{:>8}:{}'.format(direction, next))
            time.sleep(0.1)
    print('{:>8} done'.format(direction))
    return
left = threading.Thread(target=burn, args=('Left', candle.popleft))
right = threading.Thread(target=burn, args=('Right', candle.pop))
left.start()
right.start()

left.join()
right.join()


    Left:0   Right:4

   Right:3    Left:1

    Left:2   Right done

    Left done

Rotating


In [11]:
import collections
d = collections.deque(range(10))
print('Normal    :', d)
d = collections.deque(range(10))
d.rotate(2)
print('Right rotation :', d)
d = collections.deque(range(10))
d.rotate(-2)
print('Left rotation :', d)


Normal    : deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Right rotation : deque([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
Left rotation : deque([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])

Constraining the Queue Size


In [12]:
import collections
import random
random.seed(1)
d1 = collections.deque(maxlen=3)
d2 = collections.deque(maxlen=3)

for i in range(4):
    n = random.randint(0, 100)
    print('n= ', n)
    d1.append(n)
    d2.appendleft(n)
    print('D1:' ,d1)
    print('D2:', d2)


n=  17
D1: deque([17], maxlen=3)
D2: deque([17], maxlen=3)
n=  72
D1: deque([17, 72], maxlen=3)
D2: deque([72, 17], maxlen=3)
n=  97
D1: deque([17, 72, 97], maxlen=3)
D2: deque([97, 72, 17], maxlen=3)
n=  8
D1: deque([72, 97, 8], maxlen=3)
D2: deque([8, 97, 72], maxlen=3)