Insert item before each element of a list
Ian Kelly
ian.g.kelly at gmail.com
Mon Oct 8 15:42:08 EDT 2012
On Mon, Oct 8, 2012 at 1:28 PM, <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.
Using the "roundrobin" recipe from the itertools documentation:
x = [1, 2, 3]
y = list(roundrobin(itertools.repeat('insertme', len(x)), x))
More information about the Python-list
mailing list