Search code examples
pythongeneratorgenerator-expression

Is this a generator expression?


I asked a question about a list comprehension couple days ago:Elegant way to delete items in a list which do not has substrings that appear in another list

Anyway, I got a great answer to my question. It is a list comprehension:

[p for p in process_list if all(e not in p for e in exclude_list)]

I get the idea and applied it to my work. But I'm not sure if I get the e not in p for e in exclude_list part right. It looks like a generator expression to me but I'm not sure. I think it is better to ask this question in another post.

So is it a generator expression or something else?


Solution

  • Yes, all(e not in p for e in exclude_list) is a call containing a generator expression. Generator expressions that are the only argument passed to a call can omit the parentheses. Here, that's the all() function being called.

    From the Generator expressions reference documentation:

    The parentheses can be omitted on calls with only one argument.

    The all() function (as well as the companion function any() is often given a generator expression, as this allows for lazy evaluation of a series of tests. Only enough e not in p tests are executed to determine the outcome; if there is any e not in p test that is false, all() returns early and no further tests are executed.