June 2017
Beginner
352 pages
8h 39m
English
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 ...
Read now
Unlock full access