#100DaysOfCode in Python Transcripts
Chapter: Days 16-18: List comprehensions and generators
Lecture: Use generators to build a sequence

Login or purchase this course to watch this video and the rest of the course contents.
0:00 A common use case I find for generators is to build up my sequence. So, let's define a list of options. Red, yellow, blue, white, black, green, purple.
0:13 And in my older code, I will do something like, And that's fine, we just keep an internal list, and append to it and return it.
0:31 Just to show you how you can do this in a more concise way with a generator. I'm just calling it the same name, but appending _gen.
0:41 It's the same for loop, but instead of building up a new list, I'm going to use the yield keyword to yield the values one by one.
0:53 Alright, let's see what that gives us, a generator. And a way to materialize the generator at one go is to convert it into a list,
1:13 and there you go. So this is a shorter, more concise way to build up a list or sequence, and it's also faster if your data set grows,
1:21 because it's evaluated lazily. And actually to show that in practice, in the next section, I will compare a list and a generator in performance.


Talk Python's Mastodon Michael Kennedy's Mastodon