Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicating Items within a list

I am fairly new to python and am trying to figure out how to duplicate items within a list. I have tried several different things and searched for the answer extensively but always come up with an answer of how to remove duplicate items, and I feel like I am missing something that should be fairly apparent.

I want a list of items to duplicate such as if the list was [1, 4, 7, 10] to be [1, 1, 4, 4, 7, 7, 10, 10]

I know that

list = range(5)
for i in range(len(list)):
    list.insert(i+i, i)
print list

will return [0, 0, 1, 1, 2, 2, 3, 3, 4, 4] but this does not work if the items are not in order. To provide more context I am working with audio as a list, attempting to make the audio slower.

I am working with:

def slower():
     left = Audio.getLeft()
     right = Audio.getRight()
     for i in range(len(left)):
          left.insert(????)
          right.insert(????)

Where "left" returns a list of items that are the "sounds" in the left headphone and "right" is a list of items that are sounds in the right headphone. Any help would be appreciated. Thanks.

like image 677
user2884456 Avatar asked Feb 14 '23 23:02

user2884456


2 Answers

Here is a simple way:

def slower(audio):
    return [audio[i//2] for i in range(0,len(audio)*2)]
like image 59
Vaughn Cato Avatar answered Feb 23 '23 11:02

Vaughn Cato


Something like this works:

>>> list = [1, 32, -45, 12]
>>> for i in range(len(list)):
...     list.insert(2*i+1, list[2*i])
... 
>>> list
[1, 1, 32, 32, -45, -45, 12, 12]

A few notes:

  • Don't use list as a variable name.
  • It's probably cleaner to flatten the list zipped with itself.

e.g.

>>> zip(list,list)
[(1, 1), (-1, -1), (32, 32), (42, 42)]
>>> [x for y in zip(list, list) for x in y]
[1, 1, -1, -1, 32, 32, 42, 42]

Or, you can do this whole thing lazily with itertools:

from itertools import izip, chain
for item in chain.from_iterable(izip(list, list)):
    print item

I actually like this method best of all. When I look at the code, it is the one that I immediately know what it is doing (although others may have different opinions on that).

I suppose while I'm at it, I'll just point out that we can do the same thing as above with a generator function:

def multiply_elements(iterable, ntimes=2):
    for item in iterable:
        for _ in xrange(ntimes):
            yield item

And lets face it -- Generators are just a lot of fun. :-)

like image 25
mgilson Avatar answered Feb 23 '23 12:02

mgilson