107

How do I repeat each element of a list n times and form a new list? For example:

x = [1,2,3,4]
n = 3

x1 = [1,1,1,2,2,2,3,3,3,4,4,4]

x * n doesn't work

for i in x[i]:
    x1 = n * x[i]

There must be a simple and smart way.

2

14 Answers 14

151

The ideal way is probably numpy.repeat:

In [16]:

x1=[1,2,3,4]
In [17]:

np.repeat(x1,3)
Out[17]:
array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])
1
  • 3
    for the noobs, you're going to need to import numpy as np at the head of your file ;-) Aug 14, 2022 at 4:40
66

In case you really want result as list, and generator is not sufficient:

import itertools
lst = range(1,5)
list(itertools.chain.from_iterable(itertools.repeat(x, 3) for x in lst))

Out[8]: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
2
  • 2
    For those interested in efficiency, this is one of the (if not the ) fastest method listed in this post.
    – S3DEV
    Dec 17, 2019 at 9:20
  • check my answer @S3DEV
    – Holy_diver
    Jun 29, 2020 at 18:16
59

You can use list comprehension:

[item for item in x for i in range(n)]

>>> x = [1, 2, 3, 4]
>>> n = 3
>>> new = [item for item in x for i in range(n)]
#[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
8
  • pandas.Index.repeat just a call to np.repeat Jun 14, 2014 at 23:48
  • @AndyHayden, but the OP tagged pandas
    – A.J. Uppal
    Jun 14, 2014 at 23:51
  • I see that, But pandas.Index.repeat is np.repeat (as a ndarray method), there is no pandas magic here, it seems silly to call pandas for the sake of it (especially when it's not an Index!). Better to just do np.array([1, 2, 3, 4]).repeat(3). Jun 14, 2014 at 23:55
  • I don't the question has anything specifically to do with pandas tbh (I see you've already removed/rolled back a tag edit)... Jun 14, 2014 at 23:57
  • @AndyHayden I first removed it because I thought it was irrelevant. But now, I see that the OP might want to solve it with pandas.
    – A.J. Uppal
    Jun 15, 2014 at 0:02
18

A simpler way to achieve this to multiply the list x with n and sort the resulting list. e.g.

>>> x = [1,2,3,4]
>>> n = 3
>>> a = sorted(x*n)
>>> a
>>> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
2
  • 1
    For me this worked perfectly, because I also wanted to sort the list after the multiplication.
    – Albert
    May 3, 2019 at 10:59
  • 4
    Won't work if order is to be preserved x = list('NESW').
    – BSalita
    May 26, 2021 at 14:30
9

A nested list-comp works here:

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

Or to use your example:

>>> x = [1, 2, 3, 4]
>>> n = 3
>>> [i for i in x for _ in xrange(n)]
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
0
3
zAxe=[]
for i in range(5):
    zAxe0 =[i] * 3
    zAxe +=(zAxe0) # append allows accimulation of data 
1
  • 1
    Thanks for this trick; zAxe +=(zAxe0) # append allows accimulation of data
    – John Stud
    Nov 1, 2020 at 19:20
3
 [myList[i//n] for i in range(n*len(myList))]
3

way 1:

def foo():
    for j in [1, 3, 2]:
        yield from [j]*5

way 2:

from itertools import chain
l= [3, 1, 2]
chain(*zip(*[l]*3))

way 3:

sum(([i]*5 for i in [2, 1, 3]), [])
3

This will solve your issue:

x=[1,2,3,4]
n = 3
x = sorted(x * n)
2
  • Welcome to the site, but your solution is the same as an existing one.
    – johan
    Nov 12, 2020 at 5:05
  • 1
    This solution is broken for unsorted lists.
    – Konchog
    Jan 3, 2022 at 14:11
1
import itertools

def expand(lst, n):
    lst = [[i]*n for i in lst]
    lst = list(itertools.chain.from_iterable(lst))
    return lst

x=[1,2,3,4]
n=3
x1 = expand(x,3)

print(x1)

Gives:

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

Explanation:

Doing, [3]*3 gives the result of [3,3,3], replacing this with n we get [3,3,3,...3] (n times) Using a list comprehension we can go through each elem of the list and perform this operation, finally we need to flatten the list, which we can do by list(itertools.chain.from_iterable(lst))

2
  • itertools.chain(*x) these days should be written as itertools.chain.from_iterable(x)
    – mgilson
    Jun 14, 2014 at 23:13
  • 2
    No problem. I see that one relatively frequently. The problem with the former is that it resolves your iterable into a tuple by merit of the unpacking operator which partially defeats the wonderfully laziness of itertools.
    – mgilson
    Jun 14, 2014 at 23:15
0

If you want to modify the list in-place, the best way is to iterate from the back and assign a slice of what was previously one item to a list of that item n times.

This works because of slice assignment:

>>> ls = [1, 2, 3]
>>> ls[0: 0+1]
[1]
>>> ls[0: 0+1] = [4, 5, 6]
>>> ls
>>> [4, 5, 6, 2, 3]
def repeat_elements(ls, times):
    for i in range(len(ls) - 1, -1, -1):
        ls[i: i+1] = [ls[i]] * times

Demo usage:

>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]
>>> repeat_elements(b, 3)
>>> b
[1, 1, 1, 2, 2, 2, 3, 3, 3]
>>> a
[1, 1, 1, 2, 2, 2, 3, 3, 3]

(If you don't want to modify it in-place, you can copy the list and return the copy, which won't modify the original. This would also work for other sequences, like tuples, but is not lazy like the itertools.chain.from_iterable and itertools.repeat method)

def repeat_elements(ls, times):
    ls = list(ls)  # Makes a copy
    for i in range(len(ls) - 1, -1, -1):
        ls[i: i+1] = [ls[i]] * times
    return ls
0

For base Python 2.7:

    from itertools import repeat
    def expandGrid(**kwargs):
        # Input is a series of lists as named arguments
        # output is a dictionary defining each combination, preserving names
        #
        # lengths of each input list
        listLens = [len(e) for e in kwargs.itervalues()] 
        # multiply all list lengths together to get total number of combinations
        nCombos = reduce((lambda x, y: x * y), listLens) 
        iDict = {}
        nTimesRepEachValue=1 #initialize as repeating only once
        for key in kwargs.keys():
            nTimesRepList=nCombos/(len(kwargs[key])*nTimesRepEachValue)
            tempVals=[] #temporary list to store repeated
            for v in range(nTimesRepList):
                indicesToAdd=reduce((lambda x,y: list(x)+list(y)),[repeat(x, nTimesRepEachValue) for x in kwargs[key]])
                tempVals=tempVals+indicesToAdd
            iDict[key] = tempVals
            # Accumulating the number of times needed to repeat each value
            nTimesRepEachValue=len(kwargs[key])*nTimesRepEachValue
        return iDict

    #Example usage:
    expandedDict=expandGrid(letters=["a","b","c","d"],nums=[1,2,3],both=["v",3])
0
x=[1,2,3,4]
def f11(x,n):  
    l=[]
    for item in x:
        for i in range(n):
            l.append(item)
            
    return l

f11(x,2)
0

If working with array is okay,

np.array([[e]*n for e in x]).reshape(-1)

In my opinion it is very readable.

Not the answer you're looking for? Browse other questions tagged or ask your own question.