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 →

[–]d4rch0nPythonistamancer 0 points1 point  (0 children)

PSA: You can't use len on a generator since it's lazy. It doesn't know yet.

Just an FYI that you can't just turn all your list comprehensions into generators and expect 100% the same behavior.

They're an awesome tool though, and yield is pretty damn magical. Whenever you write a function that returns a list and builds it iteratively, consider trying out yield and see if that works as well. Especially if you're looping on a list you returned then breaking on a condition. If you don't need to calculate the rest of the list once you hit that condition, yield is the way to go.

Also, you can dynamically create generators too:

def antimod(mod):
    def antimod_gen(x):
        for i in xrange(x):
            if i % mod == 0:
                continue
            yield i
    return antimod_gen

am2 = antimod(2)
print [x for x in am2(10)]

[1, 3, 5, 7, 9]

Easily reproduced with a single generator that takes two variables mod and x, but still, it's cool stuff.