>>> def insert_between(iterable, fill, cond):
... iterable = iter(iterable)
... prev = next(iterable)
... yield prev
... for cur in iterable:
... if cond(prev, cur):
... yield fill
... yield cur
... prev = cur
...
>>>
>>> list(insert_between([1,2,3,4,7,8,9,15,16], 0, lambda x,y: x + 1 != y))
[1, 2, 3, 4, 0, 7, 8, 9, 0, 15, 16]
This is just as effective as you, because you still have to go through one pass on the list, and it only takes one pass. Please note that this is a generator, so you need to send it to the list if you need all the values at once.
source
share