Roy Tang

Programmer, engineer, scientist, critic, gamer, dreamer, and kid-at-heart.

Blog Notes Photos Links Archives About

DevNotes: Python's yield

I’ve been using Python for well over 10 years, and I still don’t have an intuitive mastery of one of its keywords: yield. Everytime I see it in someone’s code I need to stop and mentally remind myself what it does. I figured I’d write a devnote to help improve my recall.

Typically, yield is used in a function with a loop, like so:

def some_func(lim):
    for i in range(0, lim):
        yield i

yield means the function returns a “generator” that can be used as an iterable in a loop:

for val in some_func(5):
    print(val)

You can also straight up convert the generator into a list via something like list(some_func(5)).

The equivalent function, without using yield would be something like:

def some_func(lim):
    result = []
    for i in range(0, lim):
        result.append(i)
    return result

This is definitely the kind of function I’ve written often! Now that I’ve actually written it down, yield is rather straightforward, and hopefully it can help me shorten some of the python code I’ll be writing in the future!

Posted by under post at #software development #devnotes
Also on: twitter / 1 0 / 172 words