#100DaysOfCode in Python Transcripts
Chapter: Days 16-18: List comprehensions and generators
Lecture: List vs generator performance
0:00 I've said it a couple of times now that generators
0:03 can gain you performance when your data set grows.
0:06 So why not see that in action, and define a million years,
0:10 and loop over them and see which years are leap years.
0:14 So let me write it out and I will explain it next.
0:28 Okay so, first I have a leap years list
0:31 that builds up the list of a million years,
0:34 checking the isleap(), and I'm using calendar.isleap(),
0:37 which is a nice built in way to do that.
0:39 And the second function uses a generator,
0:41 so it's the same loop, but it yields the year.
0:44 So it's not building up the whole list in one go.
0:47 So let's use the timeit module tool,
0:49 time both functions.
0:56 And it's taking a bit.
0:58 Let's do the same for the generator.
1:06 Wow, look at that, that's milliseconds
1:09 versus nanoseconds.
1:11 So the generator is way faster.
1:14 And again, that's because it's not taking up
1:17 so much memory.
1:18 It's yielding the years one by one,
1:21 doing that lazily and saving you memory.
1:24 So that's why generator's faster.
1:27 And when you're working with large data sets,
1:29 you should definitely know about them.
1:32 And that's a wrap of day one of the list comprehension
1:35 generators lesson.