Stacks and queues

Published

2023-08-02

Stacks and queues

Now that we’ve seen lists and loops, it makes sense to present two fundamental data structures: the stack and the queue. You’ll see that implementing these in Python is almost trivial—we use a list for both, and the only difference is how we use the list.

Stacks

A stack is what’s called a last in, first out data structure (abbreviated LIFO and pronounced life-o). It’s a linear data structure where we add elements to a list at one end, and remove them from the same end.

The canonical example for a stack is cafeteria trays. Oftentimes these are placed on a spring-loaded bed, and cafeteria customers take the tray off the top and the next tray in the stack is exposed. The first tray to be put on the stack is the last one to be removed. You’ve likely seen chairs that can be stacked. The last one on is the first one off. Have you ever packed a suitcase? What’s gone in last is the first to come out. Have you ever hit the ‘back’ button in your web browser? Web browsers use a stack to keep track of the pages you’ve visited. Have you ever used ctrl-z to undo an edit to a document? Do you have a stack of dishes or bowls in your cupboard? Guess what? These are all everyday examples of stacks.

We refer to appending an element to a stack as pushing. We refer to removing an element to a stack as popping (this should sound familiar).

"

Stacks are very widely used in computer science and stacks are at the heart of many important algorithms. (In fact, function calls are managed using a stack!)

The default behavior for a list in Python is to function as a stack. Yes, that’s right, we get stacks for free! If we append an item to a list, it’s appended at one end. When we pop an item off a list, by default, it pops from the same end. So the last element in a Python list represents the top of the stack.

Here’s a quick example:

>>> stack = []
>>> stack.append("Pitchfork")
>>> stack.append("Spotify")
>>> stack.append("Netflix")
>>> stack.append("Reddit")
>>> stack.append("YouTube")
>>> stack[-1]  # see what's on top 
YouTube
>>> stack.pop()
YouTube
>>> stack[-1]  # see what's on top 
Reddit
>>> stack.pop()
Reddit
>>> stack[-1]  # see what's on top 
Netflix

So you see, implementing a stack in Python is a breeze.

Queues

A queue is a first in, first out linear data structure (FIFO, pronounced fife-o). The only difference between a stack and a queue is that with a stack we push and pop items from the same end, and with a queue we add elements at one end and remove them from the other. That’s the only difference.

What are some real world examples? The checkout line at a grocery store—the first one in line is the first to be checked out. Did you ever wait at a printer because someone had sent a job before you did? That’s another queue. Cars through a toll booth, wait lists for customer service chats, and so on—real world examples abound.

The terminology is a little different. We refer to appending an element to a queue as enqueueing. We refer to removing an element to a queue as dequeueing. But these are just fancy names for appending and popping.

"

Like stacks, queues are very widely used in computer science and are at the heart of many important algorithms.

There’s one little twist needed to turn a list into a queue. With a queue, we enqueue from one end and dequeue from the other. Like a stack, we can use append to enqueue. The little twist is that instead of .pop() which would pop from the same end, we use .pop(0) to pop from the other end of the list, and voilà, we have a queue.

Here’s a quick example:

queue = []
>>> queue.append("Fred")    # Fred is first in line
>>> queue.append("Mary")    # Mary is next in line
>>> queue.append("Claire")  # Claire ie behind Mary
>>> queue.pop(0)            # Fred has been served
'Fred'
>>> queue[0]                # now see who's in front
'Mary'
>>> queue.append("Gladys")  # Gladys gets in line
>>> queue.pop(0)            # Mary's been served
'Mary'

So you see, a list can be used as a stack or a queue. Usually, stacks and queues are used within a loop. We’ll see a little more about this in a later chapter.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).