Using Python Generators to Get the First Match
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
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.
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.
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.
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.