repeat items in a list

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Mar 26 19:28:59 EDT 2016


On 26/03/2016 22:12, beliavsky--- via Python-list 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?
>

yy = [aa for aa in xx for _ in range(nrep)]

I suggest that you try this sort of the thing at an interactive prompt, 
it's a great way to learn.

You might also want to take a look at the itertools module 
https://docs.python.org/3/library/itertools.html.  This is often used in 
building structures like the ones you've been asking about today.  To me 
it is the Swiss Army Knife of the stdlib.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list