[Tutor] Better way to insert items into a list

Peter Otten __peter__ at web.de
Sun Dec 9 10:48:53 CET 2012


Mike wrote:

> Hello everyone,
> 
> I was wondering if someone could show me a better way to achieve what
> I am trying to do.  Here is my test code:
> 
>     d=[]
>     c="00"
>     a="A,B,C,D"
>     b=a.split(',')
>     for item in b:
>         d.append(item)
>         d.append(c)
>     print tuple(d)
> 
> Basically what I want to end up with is a tuple that looks like this:
> ("A","00","B","00","C","00")...
> 
> As you can see I want to insert 00 in-between each element in the
> list.  I believe this could be done using a list comprehension?
> 
> I realize I achieved my goal, but I was wondering what other
> alternates could be done to achieve the same results.
> 
> Thanks in advance for your assistance.

I think your code is straight-forward, and that's a virtue. I suggest you 
keep it and just factor out the loop:

>>> def interleave(items, separator):
...     for item in items:
...             yield item
...             yield separator
... 
>>> print list(interleave("A,B,C,D".split(","), "00"))
['A', '00', 'B', '00', 'C', '00', 'D', '00']

If the length of the sequence (len(b) in your example) is known in advance 
the following approach is very efficient as it moves the iteration over the 
list items into C code:

>>> def interleave(items, separator):
...     result = 2 * len(items) * [separator]
...     result[::2] = items
...     return result
... 
>>> interleave("abcde", "00")
['a', '00', 'b', '00', 'c', '00', 'd', '00', 'e', '00']




More information about the Tutor mailing list