Insert item before each element of a list
Chris Kaynor
ckaynor at zindagigames.com
Mon Oct 8 15:45:42 EDT 2012
On Mon, Oct 8, 2012 at 12: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]
>
There is no need to use range and iterate over the indices:
list(itertools.chain.from_iterable(('insertme', i) for i in x))
You could simplify that even farther to a simple list expression:
[('insertme', i) for i in x]
You could also use zip and repeat:
zip(itertools.repeat('insertme'), x) # Use itertools.izip for a generator
rather than a list.
All code is untested.
>
> I appreciate any and all feedback.
>
> --Matt
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121008/4bc3bef9/attachment.html>
More information about the Python-list
mailing list