Queues in Python
The deque
object we discussed about before can be also used to represent a normal Queue
.
The usual enqueuing
and dequeuing
can be done by using the methods append
and popleft
, respectively.
>>> from collections import deque
>>> q = deque()
>>> q.append(1)
>>> q.append(2)
>>> q.append(3)
>>> q.append(4)
>>> q.popleft()
1
>>> q.popleft()
2
>>> q
deque([3, 4])
>>> len(q)
2
>>> q[0]
3
>>> q[-1]
4
Both append
and popleft
are ,
whereas looking for an element is , where is the size of the queue.