[Tutor] Better way to insert items into a list

eryksun eryksun at gmail.com
Sun Dec 9 08:43:00 CET 2012


On Sat, Dec 8, 2012 at 7:18 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> from itertools import izip_longest
> def longmux(*iterables, **kwargs):
>     # This is much easier in Python 3.

For comparison, here it is in 3.x with fillvalue as a keyword-only argument:

    from itertools import zip_longest

    def longmux(*iterables, fillvalue='00'):
        for i in zip_longest(*iterables, fillvalue=fillvalue):
            for item in i:
                yield item

I'd use zip (or itertools.izip in 2.x) and itertools repeat/chain:

    >>> from itertools import chain, repeat
    >>> a = 'ABCD'
    >>> c = '00'

    >>> tuple(chain.from_iterable(zip(a, repeat(c))))
    ('A', '00', 'B', '00', 'C', '00', 'D', '00')


More information about the Tutor mailing list