Alex Rivera | Logout

Add an item between each item already in the list

Asked 2011-05-07T11:08:33.207
39

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.

Edit
Report

1 Answer

56

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.

answered 2011-05-07T14:34:16.187

Your Answer