Lists are envious of this data structure

Hey there, 👋

How is your Python going?

In this Mathspp Insider 🐍🚀 email we’ll talk about a data structure that makes lists really envious.

This email at a glance

In this email we’ll talk about

  • the things that a list does efficiently;

  • the things that a list does inefficiently; and

  • a data structure that does what the list does, and more!

Comprehending Comprehensions poster

I just fixed the sizes of the QR codes and I added a “light theme” to it because someone emailed me asking for it so that they could print the poster.

Lists are envious of this data structure

The Python list is one of the most used data structures ever.

Across all programs in all languages in all of the world.

Do you want proof?

Easy.

Python is one of the most used languages in the world and the list is one of the most used data structures in Python.

Lists do a couple of things really well:

  • they let you store data (that’s why we say a list is a container);

  • they let you add data to the right of the list efficiently (with the method append); and

  • they let you remove data from the right of the list efficiently (with the method pop).

However, the moment you want to add/remove elements from the left of the list…

Let’s just say that’s not where a list shines.

You can do it with .pop(0) and with .insert(0, element), but those operations are inefficient.

That’s when this other data structure comes in…

collections.deque

The data structure collections.deque is a wonderful data structure that does everything a list does, and more!

You can also .append and .pop a deque, but there are additional methods like .appendleft and .popleft that let you work efficiently on the left end of the deque.

And deques have other tricks up their sleeves, thanks to the parameter maxlen that they also accept…

So, if you want to learn more about how to work with deques and the wonderful things you can do with them, take a look at this Python deque tutorial that I just wrote 😉.

ICYMI

🐍🚀 How was this email?

Login or Subscribe to participate in polls.