#100DaysOfCode in Python Transcripts
Chapter: Days 34-36: Refactoring / Pythonic code
Lecture: Refactoring 6: list comprehensions and generators

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Alright. List comprehension generators.
0:02 I did a whole class on this topic.
0:05 So, I just want to quickly recap what we learned here.
0:08 Because it should really be mentioned in refactoring.
0:12 Because it's one of those candidates
0:14 to make your code more readable, and Pythonic.
0:16 Let's get the days starting with a T and let's do
0:20 the old style keeping a list.
0:29 There you go, Tuesday and Thursday.
0:31 And again, this is fine, right?
0:32 However, you can write this in a
0:34 more concise way.
0:35 Let's use a list comprehension.
0:42 So look at that, one, two, three, four, five lines
0:45 of code reduced to one.
0:47 Awesome.
0:48 Next, let's do a quick generator example.
0:51 So, just to recap, let's make a random day generator.
0:55 So, we need some random function, and we're going
0:59 to use choice.
1:03 So while True initiates an infinite look,
1:06 I'm just going to yield the count,
1:09 and a random choice of days.
1:12 Let's initiate that generator.
1:15 I call it daysgen.
1:22 And you can see that that's the generator object.
1:24 And a generator I can call next on.
1:31 And it gives me a random day.
1:34 Lets call it again, and I get Monday again,
1:40 Tuesday, Saturday.
1:43 So it's random. Okay?
1:44 I can use it in a loop.
1:48 So let's get five more days.
1:52 There you go.
1:53 Remember that the index was at four, so now
1:55 it's five, six, seven, eight, nine random days.
1:58 And then the last nice thing to know about generators
2:01 is you can use itertools islice.
2:08 And that lets you get a slice of the generator.
2:10 Because if I now put this generator in a list,
2:13 my system would hang because this never ends.
2:16 It keeps on adding values, consuming memory,
2:19 and there's no way to stop.
2:21 There's not a StopIteration, or a stop clause in here.
2:24 islice is nice.
2:26 It can just get a slice of the generator.
2:28 Just like you do a normal slice on your list,
2:32 like first 20 items.
2:33 This is similar but works for a generator.
2:36 So, let's take an islice of daysgen,
2:39 and I want to start it at position 100
2:42 and stop it at 105.
2:43 And then it's safe to put this in a list,
2:45 because this is a finite sequence.
2:48 And there you go.
2:50 And that wraps up list comprehensions and generators.