- Mathspp Insider 🐍🚀
- Posts
- Lists are envious of this data structure
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
Today I updated my 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
); andthey 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 deque
s 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 deque
s and the wonderful things you can do with them, take a look at this Python deque tutorial that I just wrote 😉.
ICYMI
I posted a simple problem on my blog about two clocks that need to be synchronised together: https://mathspp.com/blog/problems/clock-synchronisation
I updated my Comprehending Comprehensions poster which gives an overview of how list comprehensions, dict and set comprehensions, and generator expressions work: https://mathspp.com/comprehending-comprehensions-poster
🐍🚀 How was this email? |