Not that the function is missing, I cannot think of how this could be done, except in some special cases. (l for l in lines if l.startswith('example')) is a generator object, and the variable l is local to this object. for sees only what was returned by the __next__ generator.
for very different because the result of the generator must be bound to a variable in the call area. You could write
for line in (line for line in lines if l.startswith('example')): foo(line)
safe because the two line are in different areas.
In addition, the generator does not need to return only its local variable. He can evaluate any expression. How would you cut it?
for line in (foo(line)+'bar' for line in lines if line.startswith('example')): statements
Suppose you have a list of lists
for l in (l[:] for l in list_of_lists if l): l.append('modified')
This should not be added to the source lists.
source share