Python for the .NET developer Transcripts
Chapter: The Python Language
Lecture: Concept: Python generators
0:00 The essence of a generator both in C#
0:03 and in Python is to loop or go over a sequence
0:06 and then somehow indicate
0:08 here's one, here's one, here's one
0:10 and the functions can basically run until
0:13 you say here's an item, it returns it back
0:16 and then when whoever's consuming the collection
0:19 asks for the next one, it restarts and runs to that point.
0:22 Here's the Fibonacci implementation for the infinite series
0:25 in Python, and the way you do it
0:28 is you just use the yield keyword.
0:30 I go through and set the initial state
0:32 we've a while true and that one line is
0:34 the implementation of the sequence to generate the elements
0:37 and we just, after each one, we say here's one.
0:40 That's it. We can consume it just in any for in loop
0:44 or by passing it to a list.
0:45 It's not a good idea to pass an infinite sequence
0:48 to a list, but if it were finite
0:49 if there's some reason that would stop, you know
0:51 it wasn't a while true or there's a break or something
0:53 we could actually do it that way as well.
0:55 Basically generating something that is iterable
0:58 Python's equivalent of IEnumerable.