Insert item before each element of a list

MRAB python at mrabarnett.plus.com
Mon Oct 8 15:43:12 EDT 2012


On 2012-10-08 20:28, 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.
>
Slightly better is:

y = list(itertools.chain.from_iterable(('insertme', i) for i in x))




More information about the Python-list mailing list