Home > OS >  Generators and list comprehension
Generators and list comprehension

Time:03-27

I wrote a generator like so:

def substring_gen(s):
    for i in range(len(s)):
        for j in range(i 1, len(s)  1):
            yield (s[i:j])

The above works fine. But I thought I would get fancy and try to use list comprehension like this:

def substring_gen_lc(s):
    [yield(s[i: j]) for i in range(len(s)) for j in range(i   1, len(s)   1)]

But that is not syntactically incorrect.

CodePudding user response:

yields aren’t allowed in list comprehensions. You can use a generator expression, and return it directly because it’s already the generator you need:

def substring_gen_lc(s):
    return (s[i:j] for i in range(len(s)) for j in range(i   1, len(s)   1))

But in general, there’s no need to get fancy. Using list comprehensions for side effects is a particularly bad kind of fancy, even.

CodePudding user response:

No need for the yield, it's both redundant and syntactically incorrect. It's purpose is to yield one item at a time in place of return.

Just use:

return [s[i: j] for i in range(len(s)) for j in range(i   1, len(s)   1)]
  • Related