Insert item before each element of a list

Roy Smith roy at panix.com
Mon Oct 8 22:06:50 EDT 2012


In article <mailman.1976.1349747963.27098.python-list at python.org>,
 Terry Reedy <tjreedy at udel.edu> wrote:

> On 10/8/2012 3:28 PM, 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]
> 
> 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.



More information about the Python-list mailing list