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.
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.
Use the multiplication operator to create a list with the same value repeated N times in Python, e.g. my_list = ['abc'] * 3 .
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With