Add an item between each item already in the list [duplicate]

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)