Insert item before each element of a list
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Oct 9 08:01:15 EDT 2012
On Mon, 08 Oct 2012 19:34:26 -0700, rusi wrote:
> How about a 2-paren version?
>
>>>> x = [1,2,3]
>>>> reduce(operator.add, [['insert', a] for a in x])
> ['insert', 1, 'insert', 2, 'insert', 3]
That works, but all those list additions are going to be slow. It will be
an O(N**2) algorithm.
If you're going to be frequently interleaving sequences, a helper
function is a good solution. Here's my muxer:
def mux(*iterables):
"""Muxer which yields items interleaved from each iterator or
sequence argument, stopping when the first one is exhausted.
>>> list( mux([1,2,3], range(10, 15), "ABCD") )
[1, 10, 'A', 2, 11, 'B', 3, 12, 'C']
"""
for i in itertools.izip(*iterables): # in Python 3 use builtin zip
for item in i:
yield item
Then call it like this:
py> list(mux(itertools.repeat("insert me"), range(5)))
['insert me', 0, 'insert me', 1, 'insert me', 2, 'insert me', 3, 'insert
me', 4]
--
Steven
More information about the Python-list
mailing list