repeat items in a list
Erik
python at lucidity.plus.com
Sat Mar 26 19:23:53 EDT 2016
Hi,
On 26/03/16 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 = reduce(lambda a, b: a + b, ([i] * nrep for i in xx), [])
Or, if you want to "import operator" first, you can use 'operator.add'
instead of the lambda (but you _did_ ask for a one-liner ;)).
Out of interest, why the fascination with one-liners?
E.
More information about the Python-list
mailing list