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

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to