[Tutor] Better way to insert items into a list

eryksun eryksun at gmail.com
Sun Dec 9 11:49:00 CET 2012


On Sun, Dec 9, 2012 at 4:48 AM, Peter Otten <__peter__ at web.de> wrote:
>
>>>> def interleave(items, separator):
> ...     for item in items:
> ...             yield item
> ...             yield separator
> ...

+1 for this solution if a generator function is desired. It only
requires basic Python syntax and performs well. I still prefer
itertools.chain/repeat if it's for a one-off expression.

>>>> def interleave(items, separator):
> ...     result = 2 * len(items) * [separator]
> ...     result[::2] = items
> ...     return result

This is fast if a list will do. The question asks for a tuple, though.
Including the time to build a tuple makes this approach a bit slower
than the first one.


More information about the Tutor mailing list