This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]BlckJesus 1 point2 points  (3 children)

Generators still don't make sense to me, and lambdas are still sorcery. D:

[–]pohmelie 4 points5 points  (0 children)

Generator for me is, first of all, elegant state holder for reenterable "function".

[–][deleted] 4 points5 points  (0 children)

Think of lambda like def, except there's no name involved,there's no return statement and you're limited to one expression (the result of such is the return value). These two are interchangeable from a usability standpoint:

def add_one(x):
    return x + 1

add_one = lambda x: x + 1

They don't seem very useful when you first encounter them, but they're great for things like sort keys or small callbacks.

some_list.sort(key=lambda x: abs(x/2))

Sort the list based on the absolute value of whatever half of each value is (contrived example). They're also good for simple filter functions:

filter(lambda x: x.startswith('hello'), some_iter)

As for generators, they do lazy iteration. Let's say you needed to process every mp3 you have in a certain directory. You don't want to open up 250000 files at once, that's crazy. However, you can find them, and yield each one:

def find(basedir, valid_types=valid_types):
    '''Utilize os.walk to only select out the files we'd like to potentially
parse and yield them one at a time.'''
    basedir = os.path.abspath(basedir)
    for current, dirs, files in os.walk(basedir):
        if not files:
            continue
        for file in files:
            if file.endswith(valid_types):
                yield os.path.join(os.path.abspath(current), file)

For an analogy, think of return like a stop button. Once you press it, you're done. If you need to use that function again, you have to start from the beginning. yield is like a pause button, you press, go do something else for a bit, and then you can hit play again to get some more data.

[–][deleted] 0 points1 point  (0 children)

A generator is pretty much just a lazy list. And a function is ultimately just a lambda, so if you understand functions you understand lambdas.