You can:
- Use a list comprehension to create a list of lists of repeated values
- Use
*
to unpack the list of lists into iterable arguments (each argument is one of the lists) for itertools.chain()
to treat as a single sequence
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [5, 2, 3, 2, 3, 3, 3, 3, 5, 3]
import itertools
z = list(itertools.chain(*[[x[i]] * y[i] for i in range(len(x))]))
print(z)
Output:
[0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9]
As highlighted by @chepner in a comment, the argument unpacking step using *
can be avoided by using chain.from_iterable()
instead of chain()
:
z = list(itertools.chain.from_iterable([[x[i]] * y[i] for i in range(len(x))]))