Chances are you’ve used lists, dictionaries, tuples, and maybe a set in your code. These are your basic built-in data structures Python has to offer you.

There’s a few data structures you should be aware of that are not built in, especially if you’re looking to work at a FAANG/MANGO company.

These data structures are stacks and queues. These are not Python-native data structures, but they’re easily created by using lists (for the stack) and importing a library (queue).

Stack

Think of a stack like a glass full of M&M’s. Once a bunch of M&Ms goes into the glass, you can’t get to the bottom ones unless you either:

  • Remove the ones from the top

  • Reach your fingers all the way down to the bottom (please don’t do this though)

A stack is a LIFO structure: last in, first out.

If you’ve ever used the “undo” button, it uses a stack to save the most recent action you did.

Each time you do a task, it saves what you did in the stack, with the very first task you did at the bottom all the way to the most recent task you did at the top.

Image of stack

Creating a stack is pretty simple in Python:

stack = []

def show_stack(msg):
    print(f"{msg}: {stack}")

# Push items onto the stack
stack.append("first")
show_stack("After pushing first")

stack.append("second")
show_stack("After pushing second")

stack.append("third")
show_stack("After pushing third")

# Pop items off
print("\nPopping items:")
popped = stack.pop()
show_stack(f"Popped {popped}")

popped = stack.pop()
show_stack(f"Popped {popped}")

popped = stack.pop()
show_stack(f"Popped {popped}")

When this code is ran:

After pushing first: ['first']
After pushing second: ['first', 'second']
After pushing third: ['first', 'second', 'third']

Popping items:
Popped third: ['first', 'second']
Popped second: ['first']
Popped first: []

Queue

Think of a queue as a line at an amusement park; unless you’re one of the lucky ones without an overpriced FastPass, you have to stand in line and wait your turn.

The first person who gets in line is the first person who gets onto the ride. The second person to get in line is the second person to get on the ride, and so forth.

Queues are a data structure that allows you to “enqueue” (add to the queue) in the back and then “dequeue” (remove from the queue) the front:

Depiction of a queue

Queues are a first-in, first-out data structure (FIFO), primarily designed for producer-consumer systems. A really good example of when you’d use a queue is if you have multiple processes collecting data and trying to write to a file at the same time.

It would make sense to have those individual processes to write to a file, right? Not necessarily - if you do, you could run into something like a race condition.

Instead, you’ll put your data into a queue and let some different process take care of handling your data and to the writing to the file (say, a csv for this example) to avoid issues you really shouldn’t be running into.

To use a queue, import the queue module:

from queue import Queue

q = Queue()

# Add to the queue ("enqueue")
q.put("hello")
q.put("goodbye")
q.put(1)

# dequeue each value and show it
for _ in range(q.qsize()):
    print(q.get())

Which will print the following:

"hello"
"goodbye"
1

Double Ended Queues

Just like a regular queue, a double ended queue allows you to add and remove items on both sides:

Double ended queue

There’s very few situations where you’d need this, but a fantastic example is when you have a problem that requires a sliding window.

The code for this is a bit trickier, as you need to be able to identify which side you’ll be appending or removing from:

class Deque:
    def __init__(self):
        self._data = []

    def append(self, value):
        self._data.append(value)
        print(f"After append right '{value}': {self._data}")

    def append_left(self, value):
        self._data.insert(0, value)
        print(f"After append left '{value}': {self._data}")

    def pop(self):
        if not self._data:
            raise IndexError("pop from empty deque")
        value = self._data.pop()
        print(f"Popped right '{value}': {self._data}")
        return value

    def popleft(self):
        if not self._data:
            raise IndexError("popleft from empty deque")
        value = self._data.pop(0)
        print(f"Popped left '{value}': {self._data}")
        return value

Now, if we were to have some driver code to append to different sides, we’d have something like this:

dq = Deque()

dq.append("first")
dq.append("second")
dq.append_left("zero")

print("\nPopping items:")
dq.pop()
dq.popleft()
dq.pop()

which will give us this output:

After append right 'first': ['first']
After append right 'second': ['first', 'second']
After append left 'zero': ['zero', 'first', 'second']

Popping items:
Popped right 'second': ['zero', 'first']
Popped left 'zero': ['first']
Popped right 'first': []

Happy coding!

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

or to participate

Keep Reading

No posts found