Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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?

like image 524
Claudiu Avatar asked Apr 13 '11 21:04

Claudiu


2 Answers

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 
like image 119
Jeff Mercado Avatar answered Oct 01 '22 12:10

Jeff Mercado


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"] 
like image 35
Felix Kling Avatar answered Oct 01 '22 12:10

Felix Kling