Stacks and Queues are two types of containers and as the name says, they’re used to store content. Predictable, uh? So what’s the difference between them, you might ask. Well Sir (or Madam), it’s the way data is retrieved.

Stacks support what we call LIFO (Last In, First Out). Elements are inserted at the top/end of the container, usually called push and retrieved from the same position, usually called pop.

Let’s see how we could implement this in Python:

class Stack:
    """ Simple stack implementation. """
    def __init__(self):
        self.stack = []

    def push(self, elem):
        """ Add an element to the stack. """
        self.stack.append(elem)

    def pop(self):
        """ Remove element from stack. """
        self.stack.pop()

    def get_stack(self):
        """ Get current stack. """
        return self.stack

This generic implementation is simple but serves as an example of how we could implement a Stack.

Then we have Queues which are similar, but support what we call FIFO (Fast In, First Out). Elements are inserted at the bottom/end of the container, usually called enqueue and retrieved from the first position, usually called dequeue.

Let’s see how we could implement this. Yes, that’s right, in Python:

class Queue:
    """ Simple queue implementation. """
    def __init__(self):
        self.queue = []

    def enqueue(self, elem):
        """ Add an element to the queue. """
        self.queue.append(elem)

    def dequeue(self):
        """ Remove element from queue. """
        return self.queue.pop(0)

    def get_queue(self):
        """ Get current queue. """
        return self.queue

Similar implementations, but as expected a different way of retrieving the data. As we can see, both containers can be efficiently implemented using lists/arrays. Also, we made use of Python’s append and pop methods for lists in order to insert and retrieve elements. Why reinvent the wheel?

Please note that theses data structures accept any kind of valid data simultaneously (integers, floats, arrays, strings, etc).