Add an item between each item already in the list

34,543

Solution 1

Here's a solution that I would expect to be very fast -- I believe all these operations will happen at optimized c speed.

def intersperse(lst, item):
    result = [item] * (len(lst) * 2 - 1)
    result[0::2] = lst
    return result

Tested:

>>> l = [1, 2, 3, 4, 5]
>>> intersperse(l, '-')
[1, '-', 2, '-', 3, '-', 4, '-', 5]

The line that does all the work, result[0::2] = lst, uses extended slicing and slice assignment. The third step parameter tells python to assign values from lst to every second position in l.

Solution 2

>>> list('-'.join(ls))
['a', '-', 'b', '-', 'c', '-', 'd', '-', 'e']
>>> 

Solution 3

list = ['a', 'b', 'c', 'd', 'e']
result = []
for e in list:
    result.append(e)
    result.append('-')
result.pop()

seems to work

Solution 4

This should work with any list elements:

>>> sep = '-'
>>> ls = [1, 2, 13, 14]
>>> sum([[i, '-'] for i in ls], [])[:-1]
[1, '-', 2, '-', 13, '-', 14]

Solution 5

li = ['a','b','c','d','e']
for i in xrange(len(li)-1,0,-1):
    li[i:i] = '-'

or

from operator import concat
seq = ['a','b','c','d','e']
print reduce(concat,[['-',x] for x in seq[1:]],seq[0:1])

or

li = ['a','b','c','d','e']
newli = li[0:1]
[ newli.extend(('-',x)) for x in li[1:]]
Share:
34,543
sidewinder
Author by

sidewinder

Updated on January 01, 2021

Comments

  • sidewinder
    sidewinder over 3 years

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

    Assuming I have the following list:

    ['a','b','c','d','e']
    

    How can I append a new item (in this case a -) between each item in this list, so that my list will look like the following?

    ['a','-','b','-','c','-','d','-','e']
    

    Thanks.