Maintaining State in Generators. Python

Introduction

This article continues the overview of generators in Python 3 started here

Create the file generators_demo.py and copy the code from the examples into it.

You can run the file with the command python3 generators_demo.py

Let us look at code that will return a certain number of non-repeating elements from a list

def take(count, iterable): counter = 0 for item in iterable: if counter == count: return counter += 1 yield item def distinct(iterable): seen = set() for item in iterable: if item in seen: continue yield item seen.add(item) # continue - finish current loop iteration and begin the next iteration immediately def run_pipeline(): items = [3, 6, 6, 2, 1, 1] for item in take(3, distinct(items)): print(item) run_pipeline()

distinct is a generator that yields one element at a time if that element is not in the set seen

take is also a generator - it simply takes a certain number of elements

python generators_demo.py

3 6 2

Every call of a generator function creates a new generator object

Article author: Andrei Olegovich

Banner image