The Deque Container Type in Python

Deques are a generalization of either a stack or a queue. The name is pronounced deck which is short for double ended queue. Deques are thread safe and are useful if you want to do quick appends or pops from either direction of the data structure. The list builtin type is very similar to a deque as they share many of the same functionality. However, what sets deques apart from lists is that lists are not as memory efficient for the pop() and insert() operations as the size and position of the underpinning data is modified. Below is the details of a deque class in python:

class collections.deque([iterable[, maxlen]])

Deques could be specified a fixed length with the maxlen argument; if none is specified then it can grow to an arbitrary length. Once a fixed length deque is full, if additional items are added then a corresponding number of items are discarded from the opposite end. To see the list of methods that deques support check out the collections section of the python docs.

Below is a sample of some of the methods in deques:

>>> from collections import deque
>>> cities = deque(['Los Angeles', 'Las Vegas', 'Phoneix', 'Boulder', 'NYC'])
>>> cities.append('Oakland')
>>> cities
deque(['Los Angeles', 'Las Vegas', 'Phoneix', 'Boulder', 'NYC', 'Oakland'])
>>> cities[0]
'Los Angeles'
>>> cities.appendleft('San Jose')
>>> cities.pop()
'Oakland'
>>> cities.reverse()
>>> cities
deque(['NYC', 'Boulder', 'Phoneix', 'Las Vegas', 'Los Angeles', 'San Jose'])
>>> cities.rotate(2)
>>> cities
deque(['Los Angeles', 'San Jose', 'NYC', 'Boulder', 'Phoneix', 'Las Vegas'])

Deques can be indexed, sliced, iterated over, pickled, or tested for membership. Make sure to pay attention to the performance indications. For example, indexed access is O(1) at either end but is quite slower in the middle O(n).If you need to use fast random access then lists are a better data structure. Also, starting in python3.5+, deques provide support for __add__(), __mul__(), and __imul__() methods.

============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.