#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. I did a whole class on this topic. So, I just want to quickly recap what we learned here.
0:09 Because it should really be mentioned in refactoring. Because it's one of those candidates to make your code more readable, and Pythonic.
0:17 Let's get the days starting with a T and let's do the old style keeping a list. There you go, Tuesday and Thursday. And again, this is fine, right?
0:33 However, you can write this in a more concise way. Let's use a list comprehension. So look at that, one, two, three, four, five lines
0:46 of code reduced to one. Awesome. Next, let's do a quick generator example. So, just to recap, let's make a random day generator.
0:56 So, we need some random function, and we're going to use choice. So while True initiates an infinite look, I'm just going to yield the count,
1:10 and a random choice of days. Let's initiate that generator. I call it daysgen. And you can see that that's the generator object.
1:25 And a generator I can call next on. And it gives me a random day. Lets call it again, and I get Monday again, Tuesday, Saturday.
1:44 So it's random. Okay? I can use it in a loop. So let's get five more days. There you go. Remember that the index was at four, so now
1:56 it's five, six, seven, eight, nine random days. And then the last nice thing to know about generators is you can use itertools islice.
2:09 And that lets you get a slice of the generator. Because if I now put this generator in a list, my system would hang because this never ends.
2:17 It keeps on adding values, consuming memory, and there's no way to stop. There's not a StopIteration, or a stop clause in here. islice is nice.
2:27 It can just get a slice of the generator. Just like you do a normal slice on your list, like first 20 items. This is similar but works for a generator.
2:37 So, let's take an islice of daysgen, and I want to start it at position 100 and stop it at 105. And then it's safe to put this in a list,
2:46 because this is a finite sequence. And there you go. And that wraps up list comprehensions and generators.

Talk Python's Mastodon Michael Kennedy's Mastodon