Python for the .NET Developer Transcripts
Chapter: The Python Language
Lecture: Concept: Python generators

Login or purchase this course to watch this video and the rest of the course contents.
0:00 The essence of a generator both in C# and in Python is to loop or go over a sequence and then somehow indicate here's one, here's one, here's one
0:11 and the functions can basically run until you say here's an item, it returns it back and then when whoever's consuming the collection
0:20 asks for the next one, it restarts and runs to that point. Here's the Fibonacci implementation for the infinite series in Python, and the way you do it
0:29 is you just use the yield keyword. I go through and set the initial state we've a while true and that one line is
0:35 the implementation of the sequence to generate the elements and we just, after each one, we say here's one.
0:41 That's it. We can consume it just in any for in loop or by passing it to a list. It's not a good idea to pass an infinite sequence
0:49 to a list, but if it were finite if there's some reason that would stop, you know it wasn't a while true or there's a break or something
0:54 we could actually do it that way as well. Basically generating something that is iterable Python's equivalent of IEnumerable.

Talk Python's Mastodon Michael Kennedy's Mastodon