Home » Learn Python » Iterators » Yield: Creating Generator Functions

Yield: Creating Generator Functions

An easier way to create an iterator in Python (easier than implementing __next__ and __iter__) is to use the yield keyword to create a generator function.

Although yield may at first seem counter-intuitive, it really behaves a lot like the return keyword. The difference is, you can iterate over the yielded values.

Decide if a number is prime
def is_prime(value):
    for i in range(2, value // 2 + 1):
        if value % i == 0:
            return False
    # It wasn't divisible by anything.
    # Must be prime.
    return True

Yield prime numbers up to max
def primes(max):
    for i in range(3, max):
        if is_prime(i):
            yield i

def main():
    for i in primes(50):
        print(i, end=" ")

3 5 7 11 13 17 19 23 29 31 37 41 43 47

In this code we first define a function, is_prime, that can tell us whether a single number is prime or not.

Then the primes function iterates over the numbers up to max. If a number is prime, it yields the number. This is known as a generator function.

You can then iterate over the yielded numbers.

Leave a Reply

Blog at WordPress.com.