Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 234
sidewinder Avatar asked May 07 '11 11:05

sidewinder


People also ask

How do you repeat an element in a list?

The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list.

How do you add the same value to a list multiple times in Python?

Use the multiplication operator to create a list with the same value repeated N times in Python, e.g. my_list = ['abc'] * 3 .

How do you double a list in Python?

Method #1 : Using loop This the brute force way in which this task can be performed. In this, we just add the same element again to that index element and all the contents of list are added to itself i.e doubled.

How do you add every other item to a list in Python?

You can use sum(mylist[1::2]) to add every odd items. Note: if you are dealing with huge lists or you are already memory constrained you can use itertools. islice instead of plain slicing: sum(islice(mylist, 0, len(mylist), 2)) . This will only take as much memory as one element instead of creating a whole copy.


1 Answers

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.

like image 86
senderle Avatar answered Sep 24 '22 01:09

senderle