35

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?

Claudiu
  • 224,032
  • 165
  • 485
  • 680

15 Answers15

39

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
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • 1
    note: the first arg could be called `iterable`. And the function could be called just `joinit()`. btw, the nice thing about your solution that it also works for an empty sequence (`next()` raises `StopIteration` and the generator `joinseq()` returns immediately). – jfs Apr 15 '11 at 12:03
  • @J.F.: Thanks for the tip. Naming it `iterable` would have been the first thing I did. But instead, I got into the habit of calling it `sequence` as everyone else has. :) – Jeff Mercado Apr 15 '11 at 18:18
  • 5
    I like the pun of `joinit` meaning both "join it" and "join it[erable]" – Claudiu Nov 20 '13 at 18:30
  • 5
    @claudiu I like that you came back two years later to point that out :) – undergroundmonorail Jan 13 '16 at 01:10
21

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"]
jfs
  • 399,953
  • 195
  • 994
  • 1,670
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Ah back to the last version. :) – Jeff Mercado Apr 13 '11 at 21:49
  • @JeffMercado: Yes, thanks for your comment ( I think it was you?) :) It works indeed... – Felix Kling Apr 13 '11 at 21:50
  • @JeffMercado: I know.... synchronisation problem ;) Not sure if this is really efficient though... so many iterators.... I like your solution :) But it is nice to know more than one way (despite Pythons motto that there is only one ;)) – Felix Kling Apr 13 '11 at 21:54
  • 1
    Note that the expansion of the arguments for `chain` requires iterating over all of `s`. This is a big problem for something like `intersperse(666, repeat(777))`, which the generator answers handle fine. You should be able to fix this by using `chain.from_iterable(izip(...))` instead. – Andrew Clark Apr 13 '11 at 22:03
  • @Andrew: Oh I didn't know. But makes sense now that I think about it... Thank you, will put this in my answer. – Felix Kling Apr 13 '11 at 22:05
  • This would be elegant if Python's syntax were different, I think – Claudiu Jul 04 '14 at 15:10
17

Another option that works for sequences:

def intersperse(seq, value):
    res = [value] * (2 * len(seq) - 1)
    res[::2] = seq
    return res
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
7

Solution is trivial using more_itertools.intersperse:

>>> from more_itertools import intersperse
>>> list(intersperse(666, ["once", "upon", "a", 90, None, "time"]))
['once', 666, 'upon', 666, 'a', 666, 90, 666, None, 666, 'time']

Technically, this answer isn't "writing" intersperse, it's just using it from another library. But it might save others from having to reinvent the wheel.

Jonathan Sudiaman
  • 3,364
  • 1
  • 13
  • 15
4

I would go with a simple generator.

def intersperse(val, sequence):
    first = True
    for item in sequence:
        if not first:
            yield val
        yield item
        first = False

and then you can get your list like so:

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

alternatively you could do:

def intersperse(val, sequence):
    for i, item in enumerate(sequence):
        if i != 0:
            yield val
        yield item

I'm not sure which is more pythonic

cobbal
  • 69,903
  • 20
  • 143
  • 156
  • i like this the best so far: no slicing, no doing anything specific to the iterator like calling `len`.. it aint a 1 liner but it looks nicer than the 1 liners – Claudiu Apr 13 '11 at 21:38
3
def intersperse(word,your_list):
    x = [j for i in your_list for j in [i,word]]

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

[Edit] Corrected code below:

def intersperse(word,your_list):
    x = [j for i in your_list for j in [i,word]]
    x.pop()
    return x

>>> intersperse(666, ["once", "upon", "a", 90, None, "time"])
['once', 666, 'upon', 666, 'a', 666, 90, 666, None, 666, 'time']
Phillip
  • 51
  • 2
2

I just came up with this now, googled to see if there was something better... and IMHO there wasn't :-)

def intersperse(e, l):    
    return list(itertools.chain(*[(i, e) for i in l]))[0:-1]
Nir Friedman
  • 17,108
  • 2
  • 44
  • 72
2

How about:

from itertools import chain,izip_longest

def intersperse(x,y):
     return list(chain(*izip_longest(x,[],fillvalue=y)))
rmalouf
  • 3,353
  • 1
  • 15
  • 10
1

I believe this one looks pretty nice and easy to grasp compared to the yield next(iterator) or itertools.iterator_magic() one :)

def list_join_seq(seq, sep):
  for i, elem in enumerate(seq):
    if i > 0: yield sep
    yield elem

print(list(list_join_seq([1, 2, 3], 0)))  # [1, 0, 2, 0, 3]
Ben Usman
  • 7,969
  • 6
  • 46
  • 66
1

Dunno if it's pythonic, but it's pretty simple:

def intersperse(elem, list):
    result = []
    for e in list:
      result.extend([e, elem])
    return result[:-1]
sverre
  • 6,768
  • 2
  • 27
  • 35
  • i thought of that, but i don't like that you slice the list at the end – Claudiu Apr 13 '11 at 21:21
  • I could go with initialising result to list[0], but then I'd have to first check if list is empty. [][:-1] conveniently returns [] sparing me from that problem. Seems like the generator answer is the only one so far that doesn't employ slicing. – sverre Apr 13 '11 at 21:31
1

The basic and easy you could do is:

a = ['abc','def','ghi','jkl']

# my separator is : || separator ||
# hack is extra thing : --

'--|| separator ||--'.join(a).split('--')

output:

['abc','|| separator ||','def','|| separator ||','ghi','|| separator ||','jkl']
DARK_C0D3R
  • 2,075
  • 16
  • 21
  • 2
    I like this one liner for small lists, but I'd suggest using a more unique delimiter. '--' seems like a common enough string that it'll bite someone down the line. Use something like '$)($' instead. – Ryan McGrath Jun 11 '21 at 03:27
0

This works:

>>> def intersperse(e, l):
...    return reduce(lambda x,y: x+y, zip(l, [e]*len(l)))
>>> intersperse(666, ["once", "upon", "a", 90, None, "time"])
('once', 666, 'upon', 666, 'a', 666, 90, 666, None, 666, 'time', 666)

If you don't want a trailing 666, then return reduce(...)[:-1].

Seth
  • 45,033
  • 10
  • 85
  • 120
0

Seems general and efficient:

def intersperse(lst, fill=...):
    """
    >>> list(intersperse([1,2,3,4]))
    [1, Ellipsis, 2, Ellipsis, 3, Ellipsis, 4]
    """
    return chain(*zip(lst[:-1], repeat(fill)), [lst[-1]])
dawid
  • 663
  • 6
  • 12
0

You can use Python's list comprehension:

def intersperse(iterable, element):
    return [iterable[i // 2] if i % 2 == 0 else element for i in range(2 * len(iterable) - 1)]
-1
def intersperse(items, delim):
    i = iter(items)
    return reduce(lambda x, y: x + [delim, y], i, [i.next()])

Should work for lists or generators.

Art Vandelay
  • 164
  • 2
  • 8