Skip to content
Advertisement

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?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement