pythonlist

python: most elegant way to intersperse a list with an element


Input:

intersperse(666, ["once", "upon", "a", 90, None, "time"])

Output:

["once", 666, "upon", 666, "a", 666, 90, 666, None, 666, "time"]

What's the most elegant (read: Pythonic) way to write intersperse?


Solution

  • I would have written a generator myself, but like this:

    def joinit(iterable, delimiter):
        it = iter(iterable)
        yield next(it)
        for x in it:
            yield delimiter
            yield x
    

    For 3.5+, you will need to use this version to handle empty iterables properly. PEP 479 - Change StopIteration handling inside generators changed the behavior so that a StopInteration error within a generator would be treated as an actual error instead of stopping the iteration. Makes it a little less elegant but necessary.

    def joinit(iterable, delimiter):
        try:
            it = iter(iterable)
            yield next(it)
            for x in it:
                yield delimiter
                yield x
        except StopIteration:
            return