Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Insert element(s) at beginning of generator

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?

like image 778
SLesslyTall Avatar asked Oct 16 '25 11:10

SLesslyTall


1 Answers

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]
like image 154
juanpa.arrivillaga Avatar answered Oct 19 '25 00:10

juanpa.arrivillaga