Insert item before each element of a list

Joshua Landau joshua.landau.ws at gmail.com
Fri Oct 12 13:14:49 EDT 2012


On 9 October 2012 13:55, Peter Otten <__peter__ at web.de> wrote:

> Duncan Booth wrote:
>
> > mooremathewl at gmail.com wrote:
> >
> >> What's the best way to accomplish this?  Am I over-complicating it?
> >> My gut feeling is there is a better way than the following:
> >>
> >>>>> import itertools
> >>>>> x = [1, 2, 3]
> >>>>> y = list(itertools.chain.from_iterable(('insertme', x[i]) for i in
> >>>>> range(len(x)))) y
> >> ['insertme', 1, 'insertme', 2, 'insertme', 3]
> >>
> >> I appreciate any and all feedback.
> >>
> >
> > Given the myriad of proposed solutions, I'm surprised nobody has
> suggested
> > good old list slicing:
>
> My post on gmane
>
> http://thread.gmane.org/gmane.comp.python.general/718940/focus=718947
>
> apparently didn't make it through to the list.
>
> >>>> x = [1,2,3]
> >>>> y = ['insertme']*(2*len(x))
> >>>> y[1::2] = x
> >>>> y
> > ['insertme', 1, 'insertme', 2, 'insertme', 3]
>
> An advantage of this approach -- it is usually much faster.
>

It did, at least for me. People often don't see my posts too, I've been
told. That said, sometimes people just skim threads so it may have been
that.

On topic, the best methods are either:

inserts = itertools.repeat("insert")

itertools.chain.from_iterable(zip(lst, inserts))


or the more explicit:

def interleave(*lsts):

    interleaved_in_tuples = zip(*lsts)

    return itertools.chain.from_iterable(interleaved_in_tuples)



inserts = itertools.repeat("insert")
> interleave(inserts, lst)


They explain what they want and they do it. Anyone who's interleaving
without zip needs to re-read the built-ins. The manual two-yields is good,
too, but it's much less flexible. If the speed benefits of slicing are
important but the scaling is not, you really shouldn't be using CPython.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121012/e9e72998/attachment.html>


More information about the Python-list mailing list