repeat items in a list
beliavsky at aol.com
beliavsky at aol.com
Sat Mar 26 19:54:36 EDT 2016
On Saturday, March 26, 2016 at 7:30:14 PM UTC-4, Mark Lawrence wrote:
> 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.
Thanks for the one-liner, which I prefer to the one I made up using itertools:
yy = list(chain.from_iterable([list(repeat(aa,nrep)) for aa in xx]))
More information about the Python-list
mailing list