The second stateful generator: distinct()

Now let's bring our second generator into the picture. This generator function, called distinct(), eliminates duplicate items by keeping track of which elements it's already seen in a set:

def distinct(iterable):
"""Return unique items by eliminating duplicates.

Args:
iterable: The source of the items.

Yields:
Unique elements in order from 'iterable'.
"""
seen = set()
for item in iterable:
if item in seen:
continue
yield item
seen.add(item)

In this generator we also make use of a control flow construct we have not previously seen: The continue keyword. The continue statement finishes the current iteration of the loop and begins the next iteration immediately. When executed in this case execution will be transferred back to the for statement, but as with break it can also be used with while-loops.

In this case, the continue is used to skip any values which have already been yielded. We can add a run_distinct() function to exercise distinct() as well:

def run_distinct():
items = [5, 7, 7, 6, 5, 5]
for item in distinct(items):
print(item)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset