Insert item before each element of a list

Hans Mulder hansmu at xs4all.nl
Thu Oct 11 18:21:57 EDT 2012


On 9/10/12 04:39:28, rusi wrote:
> On Oct 9, 7:34 am, rusi <rustompm... at gmail.com> 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]
> 
> Or if one prefers the different parens on the other side:
> 
>>>> reduce(operator.add, (['insert', a] for a in x))
> ['insert', 1, 'insert', 2, 'insert', 3]

Or, if you don't want to import the operator module:

sum((['insert', a] for a in x), [])

-- HansM




More information about the Python-list mailing list