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
?
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
itertools
to the rescue
- or -
How many itertools functions can you use in one line?
from itertools import chain, izip, repeat, islice def intersperse(delimiter, seq): return islice(chain.from_iterable(izip(repeat(delimiter), seq)), 1, None)
Usage:
>>> list(intersperse(666, ["once", "upon", "a", 90, None, "time"]) ["once", 666, "upon", 666, "a", 666, 90, 666, None, 666, "time"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With