Suppose I have a for loop that iterates over a generator and in this loop i’m building a list for later use:
q = []
for index, val in enumerate(['a', 'b', 'c']):
q.append(index+val)
I want to hold onto the generator without creating a function such as this:
def foo(gen):
for index, val in gen:
yield index+val
is it at all possible or is there some inherent problem I don’t see here?
I suppose it should look something like this:
iter_q = something()
for index, val in enumerate(['a', 'b', 'c']):
q.add_iteration(index+val)
OK, now that I’ve written this, it does seem quite impossible (or useless), since this for loop will have to iterate through the whole list before the “generator” is ready, which makes it just an iterator over a premade list, and not a generator in the useful sense of the object.
Posting anyway because I couldn’t find such a question myself. (plus, maybe someone still has something interesting to say about it)
If I’m understanding your question correctly, I think you might be wanting a generator expression:
That statement creates a new generator
q, which will work just like the generator returned by yourfoofunction. You don’t need to assign it to a variable either, you can create generator expressions just about anywhere, such as in a function call:There are some kinds of generators that can’t be made in generator expressions, but the most common kinds can be.