#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, sometimes building up a big list hits your performance right? It doesn't fit into memory and you can write
0:09 a generator that yields values one by one. Its like a function that pauses itself. You call it you get one value, it pauses,
0:18 you call it again, it gets you another value and it keeps your memory footprint small. Its best to write the simplest of generators next,
0:27 lets do a number generator, so def num_10 for e in range 5, and then we use the yield keyword and that's it, that's like the
0:39 smallest easiest generator is, that's stored in a variable, and that's it. Now you can get the next value from the generator
0:52 using the next keyword and that's zero and you can loop through them, like this and notice that the for loop took of at one
1:08 because zero was already used or returned, and another important thing to know about generators is that they consume their sequence once
1:19 and once you get to the end and try to go beyond that limit you get a StopIteration. If I now do next gen, boom it doesn't work, it says StopIteration
1:30 because we've exhausted the sequence right? And again, for handles this for us, so if I initiate this again, and do again the for loop,
1:47 we don't get this exception because for is smart enough to catch this for us. So, that's the simplest generator example I could come up with.


Talk Python's Mastodon Michael Kennedy's Mastodon