Skip to content

Instantly share code, notes, and snippets.

@hossainlab
Created November 3, 2018 19:00
Show Gist options
  • Select an option

  • Save hossainlab/7d9c1c4d74ef1cc071d95e5717a0bcff to your computer and use it in GitHub Desktop.

Select an option

Save hossainlab/7d9c1c4d74ef1cc071d95e5717a0bcff to your computer and use it in GitHub Desktop.
Python List as Queues(First-in, First-Out)

In this article we will learn how to use python list(built-in data structure) as Queues.

Python List as Queues(First-in, First-Out)

  • import collections.deque
  • To add an item, append()
  • To remove an item, popleft()
from collections import deque
queue = deque() 
queue.append('black') #first-in
queue.append('red')
queue.append('yellow') 
queue.append('green') #last-in
>>> queue
deque(['black', 'red', 'yellow', 'green'])
>>> queue.popleft() # first-out 
'black'
>>> queue.popleft()
'red'
>>> queue.popleft()
'yellow'
>>> queue.popleft()
'green'
>>> queue.popleft()
---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

<ipython-input-10-e488fdbdaa60> in <module>()
----> 1 queue.popleft()


IndexError: pop from an empty deque
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment