Linux

Python Collections

Up to this level of Python, you have learned data structure of Python. The collections module of Python includes implementations of several data structures that extend those found in other modules. Gradually you will learn the power of collections module. Let us discuss its power one by one.

Python Collections Deque

In simple words, A double-ended queue, or deque, allows adding and removing elements from either end.
Let us discuss Deque Operation one by one. Deque supports some list operations.
Python collection deque indexing
Deque Simple operation
Click to view code
The len() give the length of deque. You can see the right and left end of Deque from above figure.

Python deque Populating

Let us discuss more operation of Deque . As it is Double ended queue means you can add element from either side.
Python collection Populating extendleft(), appendleft()
Python Deque Populating
Click to view code
The Out-put clearly shows the code effect. The extendleft() function iterates over its input and performs the equivalent of an appendleft() for each item. The end result is that the deque contains the input sequence in reverse order.

Python deque Consuming

Python Deque can be consume from both ends or either end.
Lets discuss our next example.
Python deque consuming using pop() and popleft()
Python Deque consuming
Click to view code
Use pop() to remove an item from the right end of the deque and popleft() to remove from the left end.

Python deque Rotating

Python Deque allows you to rotate items in either side. Right rotation is taken as positive rotation. Use rotate(n) for right rotation up to n number. For left rotation use rotate(-n)
Python deque rotating using  rotate(n) and  rotate(-n)
Python Deque rotating
Click to view code
From out-put you can deduce that in right rotation, items are shifted to right direction. In left rotation, items are shifted to left direction.





admin