Skip to content

Instantly share code, notes, and snippets.

@calvingiles
Created September 9, 2014 09:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calvingiles/23e2133416648157796f to your computer and use it in GitHub Desktop.
Save calvingiles/23e2133416648157796f to your computer and use it in GitHub Desktop.
Example of yield as filter
"""
An example of using the `yield from` syntax in python 3 and a generator expression than mimics this.
"""
def yield_only_odd(i):
'''
Yield i if and only if i is odd.
This is a generator that yields zero or one times.
'''
if i % 2 == 1:
yield i
def odd_numbers(n):
'''
Yield odd numbers in the half open set [0,n).
'''
for i in range(n):
yield from yield_only_odd(i)
# Demonstration of yield as a filter
print(list(odd_numbers(10)))
# Demonstration of the same in generator expressions
print(list(j for i in range(0, 10, 1) for j in yield_only_odd(i)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment