repeat items in a list
Antonio Caminero Garcia
tonycamgar at gmail.com
Sun Mar 27 04:30:01 EDT 2016
On Sunday, March 27, 2016 at 10:02:44 AM UTC+2, Antonio Caminero Garcia wrote:
> 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))
I prefer the commented solution :).
[ritem for item in sequence for ritem in [item]*nrep] # O(len(sequence)*2nrep)
and the chain solution would be # O(len(sequence)*nrep). The constants ate gone so I prefer the first one for its readibility.
On a practical level:
https://bpaste.net/show/fe3431a13732
More information about the Python-list
mailing list