#100DaysOfCode in Python Transcripts
Chapter: Days 4-6: Collections module
Lecture: Deque: when lists become slow

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Next up are deques. deques are stacks and queues. They're useful if you want to insert and append on both sides of the sequence.
0:11 In this section, I will compare them to lists. I mean, lists are your best friends. You will use them everywhere.
0:16 They're easy to use and for 80% of your use cases, or maybe 90%, they're just adequate. But lists come with a downside which if you have
0:26 to move items around, they get less performant. And in this exercise, I will create a list and a deque
0:33 of ten million ints and a function to do random inserts and deletes and then we're going to use timeit, to see how they perform.
0:42 So let's create the two sequences. First I want a list. I can just use the range. Let me the get the zeros right. One, two, three, one, two three.
0:55 That's ten million. And let's make a deque. You create that big deque. Range, one, two, three, one, two three.
1:06 Next, we create an insert and delete function that takes a sequence... and we do, for... Underscore... In braces.. Index equals random...
1:25 Choice. And a random choice takes a sequence and just randomly chooses one item. I store that into index and I remove it.
1:43 So that index is like a random location in the sequence. I'm going to remove the item that's at that index. And I'm going to do an insert of index
1:56 at index and I'm just going to insert the same value of index, doesn't really matter. I'm going to use timeit to time this function
2:06 for both the list and the deque. Here we have the timeit module. And we're going to call it with insert and delete
2:15 on the list, and the list we defined here above. You can see this took a little bit. And now let's do the same for the deque which we defined here.
2:36 And although it seems to take a little bit as well. Here we're talking about milliseconds and here we're talking about microseconds.
2:46 Here it also run like 10,000 loops. This one was slower so it reduced to one loop. So deque performs at a fraction of the list
2:55 and that's because inserting and removing at both sides of the sequence are more efficient in a deque than a list.
3:03 A list has to move all the items around and that's expensive. I encourage you to look at the docs because there are a few
3:11 other data types that are interesting and you can read about ChainMap, for example. An OrderedDict is another good data type to know about.
3:20 Although I think in Python 3.6, dicts are becoming ordered by default. That concludes day one.


Talk Python's Mastodon Michael Kennedy's Mastodon