Insert item before each element of a list
steve+comp.lang.python at pearwood.info
Fri Oct 12 04:16:20 CEST 2012
On Fri, 12 Oct 2012 00:21:57 +0200, Hans Mulder wrote:
> 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), )
Which is also O(N**2) like the reduce solution above.
That means that it will seem perfectly fine when you test it using a a
hundred or so items, then some day you'll pass it a list with ten million
items and it will take 36 hours to complete.
I'm serious by the way. By my tests, increasing the number of items in
the list by a factor of ten increases the time taken by between 30 and
More information about the Python-list