If I have a generator, e.g.:
g = (i for i in range(10))
and later I want to update the generator so that the first element(s) yielded is now some other element(s), what is the most "pythonic" way to do this?
Clearly, I could define a basic generator extender function such as:
def extend(generator, new_elements):
for element in new_elements:
yield element
for element in generator:
yield element
but I am wondering if this is necessary or if there is some better way to do this?
You could use itertools.chain
for this:
>>> from itertools import chain
>>> g = (i for i in range(10))
>>> list(chain(['a','b','c'], g))
['a', 'b', 'c', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With