user2884456
user2884456

Reputation: 49

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.

Upvotes: 4

Views: 136

Answers (5)

mgilson
mgilson

Reputation: 309821

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. :-)

Upvotes: 2

Alex.Bullard
Alex.Bullard

Reputation: 5563

a = [0,1,2,3]
list(reduce(lambda x,y: x + y, zip(a,a))) #=> [0,0,1,1,2,2,3,3]

Upvotes: 0

Vaughn Cato
Vaughn Cato

Reputation: 64298

Here is a simple way:

def slower(audio):
    return [audio[i//2] for i in range(0,len(audio)*2)]

Upvotes: 6

Hammer
Hammer

Reputation: 10329

This might not be the fastest way but it is pretty compact

a = range(5)
list(reduce(operator.add, zip(a,a)))

a then contains

[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]

Upvotes: 0

pfnuesel
pfnuesel

Reputation: 15300

listOld = [1,4,7,10]
listNew = []

for element in listOld:
    listNew.extend([element,element])

Upvotes: 0

Related Questions