#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
0:02
is to build up my sequence.
0:04
So, let's define a list of options.
0:07
Red, yellow, blue, white, black, green, purple.
0:12
And in my older code, I will do something like,
0:22
And that's fine, we just keep an internal list,
0:26
and append to it and return it.
0:30
Just to show you how you can do this in a more
0:32
concise way with a generator.
0:35
I'm just calling it the same name,
0:38
but appending _gen.
0:40
It's the same for loop,
0:42
but instead of building up a new list,
0:44
I'm going to use the yield keyword
0:46
to yield the values one by one.
0:52
Alright, let's see what that gives us, a generator.
0:59
And a way to materialize the generator
1:03
at one go is to convert it into a list,
1:12
and there you go. So this is a shorter, more concise way
1:14
to build up a list or sequence,
1:16
and it's also faster if your data set grows,
1:20
because it's evaluated lazily.
1:23
And actually to show that in practice,
1:24
in the next section, I will compare a list
1:27
and a generator in performance.