On 26Mar2016 15:12, [email protected] <[email protected]> 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?
Sure. As with all one liners, there comes a degree of complexity when it gets in the way of readability; you must decide what is better in your use case.
Look up the chain() function from the itertools module. Generate 2 (or nrep) length lists from each element of the original list and chain() them together. That gets you an iterable of all the elements. If you really need a list out the end instead of the iterable of the elements, convert the iterable to a list (hint: lists can be initialised with iterables).
Cheers, Cameron Simpson <[email protected]> -- https://mail.python.org/mailman/listinfo/python-list
