Insert item before each element of a list

rusi rustompmody at gmail.com
Mon Oct 8 22:34:26 EDT 2012


On Oct 9, 7:06 am, Roy Smith <r... at panix.com> wrote:
> In article <mailman.1976.1349747963.27098.python-l... at python.org>,
>  Terry Reedy <tjre... at udel.edu> wrote:
>
>
>
>
>
>
>
>
>
> > On 10/8/2012 3:28 PM, mooremath... 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]
>
> > The straightforward, crystal-clear, old-fashioned way
>
> >  >>> lst = []
> >  >>> for item in [1,2,3]:
> >    lst.append('insert me')
> >    lst.append(item)
>
> I'm going to go with this one.  I think people tend to over-abuse list
> comprehensions.  They're a great shorthand for many of the most common
> use cases, but once you stray from the simple examples, you quickly end
> up with something totally obscure.
>
> > y = list(itertools.chain.from_iterable(('insertme', x[i]) for i in range(len(x))))
>
> A statement ending in four close parens is usually going to be pretty
> difficult to figure out.  This is one where I had to pull out my pencil
> and start pairing them off manually to figure out how to parse it.

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]



More information about the Python-list mailing list