#100DaysOfCode in Python Transcripts
Chapter: Days 16-18: List comprehensions and generators
Lecture: Generators - the basics

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Next up are generators,
0:02 sometimes building up a big list
0:04 hits your performance right?
0:06 It doesn't fit into memory and you can write
0:08 a generator that yields values one by one.
0:11 Its like a function that pauses itself.
0:15 You call it you get one value, it pauses,
0:17 you call it again, it gets you another value
0:20 and it keeps your memory footprint small.
0:22 Its best to write the simplest of generators next,
0:26 lets do a number generator, so def num_10
0:31 for e in range 5,
0:34 and then we use the yield keyword
0:36 and that's it, that's like the
0:38 smallest easiest generator is,
0:41 that's stored in a variable,
0:47 and that's it.
0:48 Now you can get the next value from the generator
0:51 using the next keyword and that's zero
0:56 and you can loop through them, like this
1:04 and notice that the for loop took of at one
1:07 because zero was already used or returned,
1:12 and another important thing to know about generators
1:16 is that they consume their sequence once
1:18 and once you get to the end and try to go beyond
1:22 that limit you get a StopIteration.
1:24 If I now do next gen, boom
1:26 it doesn't work, it says StopIteration
1:29 because we've exhausted the sequence right?
1:32 And again, for handles this for us,
1:35 so if I initiate this again,
1:41 and do again the for loop,
1:46 we don't get this exception
1:49 because for is smart enough to catch this for us.
1:51 So, that's the simplest generator example
1:54 I could come up with.