repeat items in a list

Peter Otten __peter__ at web.de
Wed Mar 30 11:52:09 EDT 2016


Michael Selik wrote:

> I prefer itertools.chain.from_iterable to the sum trick.
> 
>>>> from itertools import chain
>>>> lst = list('abc')
>>>> list(chain.from_iterable([s]*3 for s in lst))
> ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']

If you want to make this completely lazy:

>>> from functools import partial
>>> from itertools import repeat, chain
>>> items = list("abc")
>>> list(chain.from_iterable(map(partial(repeat, times=3), items)))
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']





More information about the Python-list mailing list