Using Python Generators to Get the First Match
00:00 Using Python Generators to Get the First Match. Python generator iterators are memory-efficient iterables that can be used to find the first element in a list or any iterable.
00:13
They’re a core feature of Python being used extensively under the hood. It’s likely you’ve already used generators without even knowing it. The potential issue with generators is that they’re a bit more abstract and, as such, not quite as readable as for
loops.
00:29 You do get some performance benefits from generators, but these are often negligible when the importance of readability is taken into consideration. That said, using them can be fun and level up your Python game.
00:44 In Python, you can make a generator in various ways, but in this course, you’ll be working with generator comprehensions.
00:56
Once you’ve defined a generator iterator, you can then call the next()
function with the generator as an argument, producing the countries one by one until the countries
list is exhausted.
01:06 To find the first element matching a certain criteria in a list, you can add a conditional expression to the generator comprehension, so the resulting iterator will only yield items that match the criteria.
01:18
In the example seen on-screen, you use a conditional expression to generate items based on whether the population
attribute is over one hundred million.
01:37
So now the generator will only produce dictionaries with a population
attribute of over one hundred million. This means that the first time you call next()
with a generator iterator, it will yield the first element that you’re looking for in the list, just like the for
loop version.
01:54
Note that you’ll get an exception if you call next()
and there’s no match or the generator is exhausted. To prevent this, you can pass in a default argument to next()
.
02:07
Once the generator is finished producing matches, it will return the default value that’s been passed in. Since you’re returning None
, you get no output in the REPL.
02:20
If you hadn’t passed in the default value, you would get a StopIteration
exception.
02:30
In terms of readability, a generator isn’t quite as natural as a for
loop, so why would you use one for this purpose? Well, in the next section of the course, you’ll be doing a quick performance comparison to find out.
Become a Member to join the conversation.