How to repeat each of a Python list's elements n times with itertools only?

iteration, list, performance, python, python-itertools

Solution

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]

Problem

I have a list with numbers: `numbers = [1, 2, 3, 4]`. I would like to have a list where they repeat `n` times like so (for `n = 3`): `[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]`. The problem is that I would like to only use `itertools` for this, since I am very constrained in performance. I tried to use this expression: `list(itertools.chain.from_iterable(itertools.repeat(numbers, 3)))` But it gives me this kind of result: `[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]` which is obviously not what I need. Is there a way to do this with `itertools` only, without using sorting, loops and list comprehensions? The closest I could get is: `list(itertools.chain.from_iterable([itertools.repeat(i, 3) for i in numbers]))`, but it also uses list comprehension, which I would like to avoid.

Original source

Related problems