Roy Tang

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

Blog Photos Links Archives About

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 / Syndicated: / 1 0 / 172 words

See Also

tyler garrett 🐸

Roy Tang is a:

roytang.net is a personal site, an E/N site, and kind of a commonplace book; I post about a random assortment of topics that interest me including software development, Magic the Gathering, pop culture, gaming, and tech life. This site is perpetually under renovation.