Skip to content

Instantly share code, notes, and snippets.

@matthewpoer
Last active June 3, 2021 15:11
Show Gist options
  • Save matthewpoer/a51cbec079118dbdf1b7b9370d85b740 to your computer and use it in GitHub Desktop.
Save matthewpoer/a51cbec079118dbdf1b7b9370d85b740 to your computer and use it in GitHub Desktop.

Code samples to demonstrate Python iterators and the use of yield statements to create a generator.

Examples based directly on the instruction from Programiz' YouTube Channel

In the second video, the insturctor summarizes "yield" in the following way:

The difference between yield and return is that the return terminates the function completely while yield pauses the function, saving all it's states for next successive calls

class Even:
def __init__(self, max):
self.n = 2
self.max = max
def __iter__(self):
return self
def __next__(self):
if self.n <= self.max:
result = self.n
self.n += 2
return result
else:
raise StopIteration
numbers = Even(10)
print(next(numbers)) # 2
print(next(numbers)) # 4
print(next(numbers)) # 6
print(next(numbers)) # 8
def even_generator_static_yield():
n = 0
n+=2
yield n
n+=2
yield n
n+=2
yield n
n+=2
yield n
numbers = even_generator_static_yield()
print(next(numbers)) # 2
print(next(numbers)) # 4
print(next(numbers)) # 6
print(next(numbers)) # 8
def even_generator_dynamic_yield(max):
n = 0
while n <= max:
yield n
n += 2
numbers = even_generator_dynamic_yield(10)
print(next(numbers)) # 2
print(next(numbers)) # 4
print(next(numbers)) # 6
print(next(numbers)) # 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment