Insert item before each element of a list
Terry Reedy
tjreedy at udel.edu
Mon Oct 8 21:58:54 EDT 2012
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)
>>> lst
['insert me', 1, 'insert me', 2, 'insert me', 3]
Paul Rubin's list(gfunc(prefix, lst)) is similar in execution.
--
Terry Jan Reedy
More information about the Python-list
mailing list