#100DaysOfCode in Python Transcripts
Chapter: Days 16-18: List comprehensions and generators
Lecture: List vs generator performance
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
I've said it a couple of times now that generators can gain you performance when your data set grows.
0:07
So why not see that in action, and define a million years, and loop over them and see which years are leap years.
0:15
So let me write it out and I will explain it next. Okay so, first I have a leap years list
0:32
that builds up the list of a million years, checking the isleap(), and I'm using calendar.isleap(), which is a nice built in way to do that.
0:40
And the second function uses a generator, so it's the same loop, but it yields the year. So it's not building up the whole list in one go.
0:48
So let's use the timeit module tool, time both functions. And it's taking a bit. Let's do the same for the generator.
1:07
Wow, look at that, that's milliseconds versus nanoseconds. So the generator is way faster. And again, that's because it's not taking up so much memory.
1:19
It's yielding the years one by one, doing that lazily and saving you memory. So that's why generator's faster.
1:28
And when you're working with large data sets, you should definitely know about them. And that's a wrap of day one of the list comprehension
1:36
generators lesson.