Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate each member in a list

I want to write a function that reads a list [1,5,3,6,...] and gives [1,1,5,5,3,3,6,6,...]. Any idea how to do it?

like image 973
ariel Avatar asked Mar 15 '10 17:03

ariel


People also ask

How do you repeat elements in a list?

Using the * Operator 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.

Can list contain duplicate items?

Python list can contain duplicate elements.

How do you duplicate a value in Python?

In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object.


4 Answers

>>> a = range(10)
>>> [val for val in a for _ in (0, 1)]
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]

N.B. _ is traditionally used as a placeholder variable name where you do not want to do anything with the contents of the variable. In this case it is just used to generate two values for every time round the outer loop.

To turn this from a list into a generator replace the square brackets with round brackets.

like image 67
Dave Kirby Avatar answered Oct 10 '22 10:10

Dave Kirby


>>> a = [1, 2, 3]
>>> b = []
>>> for i in a:
    b.extend([i, i])


>>> b
[1, 1, 2, 2, 3, 3]

or

>>> [a[i//2] for i in range(len(a)*2)]
[1, 1, 2, 2, 3, 3]
like image 42
SilentGhost Avatar answered Oct 10 '22 09:10

SilentGhost


numpy.repeat does what you want:

import numpy as np
yourList = [1,5,3,6]
n = 2
list(np.repeat(yourList, n))

result:

[1, 1, 5, 5, 3, 3, 6, 6]

If you don't mind using numpy arrays you can also omit the list() call in the last line.

like image 13
PDiracDelta Avatar answered Oct 10 '22 09:10

PDiracDelta


If you already have the roundrobin recipe described in the documentation for itertools—and it is quite handy—then you can just use

roundrobin(my_list, my_list)
like image 11
Hank Gay Avatar answered Oct 10 '22 08:10

Hank Gay