Suppose I have an iterator, and I want to add some elements before or after it. The only way I can think of to do this is to use an explicit loop:
def myiter(other_iter):
yield "First element"
for item in other_iter:
yield item
yield "Last element"
Is there a better or more efficient way to do this? Is there a function with a name like yield_items_from that can be used like this?
def myiter(other_iter):
yield "First element"
yield_items_from(other_iter)
yield "Last element"
Edit:
Ok, I oversimplified my example. Here’s a better one:
Suppose I have an iterator other_iter that returns an ascending sequence of nonnegative integers. I want to return an iterator that counts up from zero, returning 1 for numbers returned by other_iter and 0 otherwise. For example, if other_iter yields [1,4,5,7], I want to yield [0,1,0,0,1,1,0,1]. Is there an efficient and readable way to do this?
No, there is nothing like
yield_items_from, although there is a draft proposal for adding one to Python 3.X in PEP 380.For current Python, the explicit loop is the only way to yield from a sub-iterator. However, it’s reasonably efficient, and it is the idiomatic way to do it, so you shouldn’t be too bothered by the verbosity.
If all you need to do is add new items to the front or back of the iterator, then you can simply use
itertools.chainto create a new iterator. You can use it to chain several iterators together, or append/prepend individual items by wrapping them in a list.