#100DaysOfCode in Python Transcripts
Chapter: Days 4-6: Collections module
Lecture: Concepts: what did we learn
0:00 Next up are deques.
0:02 deques are stacks and queues.
0:04 They're useful if you want to insert and append
0:08 on both sides of the sequence.
0:10 In this section, I will compare them to lists.
0:12 I mean, lists are your best friends.
0:14 You will use them everywhere.
0:15 They're easy to use and for 80% of your use cases,
0:19 or maybe 90%, they're just adequate.
0:22 But lists come with a downside which if you have
0:25 to move items around, they get less performant.
0:28 And in this exercise, I will create a list and a deque
0:32 of ten million ints and a function to do random inserts
0:36 and deletes and then we're going to use timeit,
0:39 to see how they perform.
0:41 So let's create the two sequences.
0:44 First I want a list.
0:47 I can just use the range.
0:50 Let me the get the zeros right.
0:52 One, two, three, one, two three.
0:54 That's ten million.
0:56 And let's make a deque.
0:58 You create that big deque.
1:01 Range, one, two, three, one, two three.
1:05 Next, we create an insert and delete function
1:11 that takes a sequence...
1:14 and we do, for...
1:19 In braces..
1:21 Index equals random...
1:29 And a random choice takes a sequence
1:33 and just randomly chooses one item.
1:36 I store that into index
1:38 and I remove it.
1:42 So that index is like a random location in the sequence.
1:46 I'm going to remove the item that's at that index.
1:51 And I'm going to do an insert of index
1:55 at index and I'm just going to insert
1:58 the same value of index, doesn't really matter.
2:01 I'm going to use timeit to time this function
2:05 for both the list and the deque.
2:07 Here we have the timeit module.
2:10 And we're going to call it with insert and delete
2:14 on the list, and the list we defined here above.
2:21 You can see this took a little bit.
2:24 And now let's do the same for the deque
2:29 which we defined here.
2:35 And although it seems to take a little bit as well.
2:38 Here we're talking about milliseconds
2:42 and here we're talking about microseconds.
2:45 Here it also run like 10,000 loops.
2:47 This one was slower so it reduced to one loop.
2:51 So deque performs at a fraction of the list
2:54 and that's because inserting and removing
2:57 at both sides of the sequence are more efficient
3:00 in a deque than a list.
3:02 A list has to move all the items around
3:05 and that's expensive.
3:06 I encourage you to look at the docs because there are a few
3:10 other data types that are interesting
3:13 and you can read about ChainMap, for example.
3:16 An OrderedDict is another good data type to know about.
3:19 Although I think in Python 3.6,
3:21 dicts are becoming ordered by default.
3:25 That concludes day one.