How to repeat each of a Python list's elements n times with itertools only?
Firstly, using functions from itertools
won't necessarily be faster than a list comprehension — you should benchmark both approaches. (In fact, on my machine it's the opposite).
Pure list comprehension approach:
>>> numbers = [1, 2, 3, 4]
>>> [y for x in numbers for y in (x,)*3]
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
Using chain.from_iterable()
with a generator expression:
>>> from itertools import chain, repeat
>>> list(chain.from_iterable(repeat(n, 3) for n in numbers))
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
Since you don't want to use list comprehension, following is a pure (+zip
) itertools
method to do it -
from itertools import chain, repeat
list(chain.from_iterable(zip(*repeat(numbers, 3))))
# [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
Think you were very close, just rewriting the comprehension to a generator:
n = 3
numbers = [1, 2, 3, 4]
list(itertools.chain.from_iterable((itertools.repeat(i, n) for i in numbers)))