repeat items in a list

Antonio Caminero Garcia tonycamgar at gmail.com
Sun Mar 27 04:02:14 EDT 2016


On Saturday, March 26, 2016 at 11:12:58 PM UTC+1, beli... at aol.com wrote:
> I can create a list that has repeated elements of another list as follows:
> 
> xx = ["a","b"]
> nrep = 3
> print xx
> yy = []
> for aa in xx:
>     for i in range(nrep):
>         yy.append(aa)
> print yy
> 
> output:
> ['a', 'b']
> ['a', 'a', 'a', 'b', 'b', 'b']
> 
> Is there a one-liner to create a list with repeated elements?

What about this?

def rep_elements(sequence, nrep):
    #return [ritem for item in sequence for ritem in [item]*nrep]
    return list(chain.from_iterable(([item]*nrep for item in sequence)))

sequence = ['h','o','l','a']
print(rep_elements(sequence,  3))



More information about the Python-list mailing list