Python's Collections Module: deque
Tags: python, collections, codenewbie, deque
Published: 2021-06-19 12:30:28

## Deque, short for Double Ended Queue

It is a _list-like_ container with fast appends and pops on either end.

Deques are a generalization of stacks and queues. 

Deques support thread-safe, memory efficient _appends_ and _pops_ from either side of the `deque` with approximately the same **O(1)** performance in either direction.

### Importing `deque`
```python
from collections import deque
```

## Creating a `deque` container
```python
""" deques can be created from any iterable
using : "deque(iterable)" syntax
"""

d1 = deque([1, 2, 3, 3, 4, 5])  # from list
d2 = deque(("Kathan", 19, 'idc'))  # from tuple
d3 = deque("Followme")  # from string

# dictionary is an iterable of keys btw,
d4 = deque({"name": "R", "age": 1})  # from dict
print(d1, d2, d3, d4, sep='\n')

"""OUTPUT
deque([1, 2, 3, 3, 4, 5])
deque(['Kathan', 19, 'idc'])
deque(['F', 'o', 'l', 'l', 'o', 'w', 'm', 'e'])
deque(['name', 'age'])
"""
```
### The `maxlen` argument
We can also pass an optional argument `maxlen` which determines the size of deque.

`deque(iterable, maxlen)`
> 📑If `maxlen` is not specified or is **None**, deques may grow to an arbitrary length. 

Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the __opposite__ end.

This thing will make sense more, if we know how to update a deque after instantiation. Let's discuss those methods now, 

## `append,` `appendleft`, `pop`, `popleft` methods
```python
my_deque = deque([1, 2, 3, 4, 5])

# append(y) => appends y to right side
my_deque.append(6)
print("After my_deque.append(6) =>", my_deque)

# appendleft(y) => appends y to left side
my_deque.appendleft(0)
print("After my_deque.appendleft(0) =>", my_deque)

# pop() => Remove and return an element from the right side
my_deque.pop()
print("After my_deque.pop()=>", my_deque)

# popleft() =>Remove and return an element from the left side
my_deque.popleft()
print("After my_deque.popleft()=>", my_deque)

"""OUTPUT
After my_deque.append(6) => deque([1, 2, 3, 4, 5, 6])
After my_deque.appendleft(0) => deque([0, 1, 2, 3, 4, 5, 6])
After my_deque.pop()=> deque([0, 1, 2, 3, 4, 5])
After my_deque.popleft()=> deque([1, 2, 3, 4, 5])
"""
```
> 📑 The important part here is that both append methods don't return anything, they perform __inplace__ modifications!

## `extend`, `extendleft` methods
```python
my_deque = deque([1, 2, 3])

"""extend(iterable)
Extend the right side of the deque by 
appending elements from the iterable argument
"""
my_deque.extend([4, 5, 6])
print("After extend:", my_deque)

"""extendleft(iterable)
Extend the left side of the deque by appending 
elements from iterable.
"""
my_deque.extendleft([0, -1, -2])
print("After extendleft:",my_deque)

"""OUTPUT
After extend: deque([1, 2, 3, 4, 5, 6])
After extendleft: deque([-2, -1, 0, 1, 2, 3, 4, 5, 6])
"""
```
>📑 If you notice in the `extendleft(iterable)` method, the elements are inserted in __reversed__ order i.e. the last element of input iterable is the first in our updated `deque`. This is because we perform _series of left appends_ by taking elements from start to end (from our iterable).

## More methods
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/49ya4hvp6qrl3riuuq16.png)
 
> 🔮 `deque` is a very powerful container, and it has loads of functionalities! I have discussed most of them here but feel free to check out the [documentation](https://docs.python.org/3/library/collections.html#collections.deque) for some extra goodies.

And that wraps our discussion on __collections__ module. I hope you enjoyed the extensive coverage :) I hope you join me again for some other adventure!

Untill then, Enjoy Programming 🥳

## References
https://docs.python.org/3/library/collections.html#module-collections