deque

Another similar data structure, deque, also lives in the collections module and is similar to queues, but with one nuance. As they are double-ended queues, which is what the name refers to, they can efficiently add and release values from both sides, rather than from one end.

Let's have a look at the following code:

from collections import deque
D = deque(['wash dishes', 'water flowers', 'check mail'])

As we mentioned, deque can efficiently remove values both from the right and the left end of the queue. In the following code, pop represents the rightmost end, while popleft pulls the value from the left side:

>>> D.pop()
'check mail'

>>> D.popleft()
'wash dishes'

Similar to .pop_left(), deque has the .append_left() and .extend_left() methods. They also support rotation, where items move from the left end to the right, either in one direction or the opposite direction.

Queues, stacks, and dequeues are highly performant data structures for very specific tasks. For example, dequeues are used in certain task scheduling algorithms, where different workers can add tasks for themselves on one side and—if their job is done—steal another worker's job from the other side. Still, these kind of problems are very low-level and specific. Throughout this book, we will not use any of them, but it is still important to know about them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.214.21