Can I "splice" in the contents of an iterator into my own iterator in Python? -


suppose have iterator, , want add elements before or after it. way can think of use explicit loop:

def myiter(other_iter):     yield "first element"     item in other_iter:         yield item     yield "last element" 

is there better or more efficient way this? there function name yield_items_from can used this?

def myiter(other_iter):     yield "first element"     yield_items_from(other_iter)     yield "last element" 

edit:

ok, oversimplified example. here's better one:

suppose have iterator other_iter returns ascending sequence of nonnegative integers. want return iterator counts zero, returning 1 numbers returned other_iter , 0 otherwise. example, if other_iter yields [1,4,5,7], want yield [0,1,0,0,1,1,0,1]. there efficient , readable way this?

no, there nothing yield_items_from, although there draft proposal adding 1 python 3.x in pep 380.

for current python, explicit loop way yield sub-iterator. however, it's reasonably efficient, , idiomatic way it, shouldn't bothered verbosity.

if need add new items front or of iterator, can use itertools.chain create new iterator. can use chain several iterators together, or append/prepend individual items wrapping them in list.

new_iter = itertools.chain(['prefix item'], old_iter, appended_iter) 

Comments

Popular posts from this blog

Javascript line number mapping -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -