repeat items in a list
Cameron Simpson
cs at zip.com.au
Sat Mar 26 19:05:47 EDT 2016
More information about the Python-list mailing list
Sat Mar 26 19:05:47 EDT 2016
- Previous message (by thread): repeat items in a list
- Next message (by thread): repeat items in a list
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 26Mar2016 15:12, beliavsky at aol.com <beliavsky 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? 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 <cs at zip.com.au>
- Previous message (by thread): repeat items in a list
- Next message (by thread): repeat items in a list
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list