Stacks and Queues using Python

queue-road-signStacks and Queues are two key data structures often used in programming.

A queue is a FIFO data structure: First-In First-Out in other words, it is used to implement a first come first served approach. An item that is added (enqueue) at the end of a queue will be the last one to be accessed (dequeue).

A stack is a FILO data strucutre: First-In Last-Out. Imagine a stack of books piled up on a table. When you add (push) a book on top of the pile, it will be the first book that you will then take (pop) from the pile (stack).

queue-diagram

stack-diagram

Both stacks and queues can easily be implemented in Python using a list and the append(), pop() and remove() functions.

In the following trinket we are creating our own classes, Queue and Stack. Using Object Oriented Programming (OOP) enables us to prevent direct access to the list (defined as a private attribute – This is an example of encapsulation a key concept in OOP). It also enables us to create and name our own methods, pop(), push(), enqueue() and dequeue() to match the terminology used when using stacks or queues.

Share Button