Insert item before each element of a list
Peter Otten
__peter__ at web.de
Tue Oct 9 08:55:20 EDT 2012
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.
More information about the Python-list
mailing list