Given the following lists:
a = [0, 5, 1]
b = [1, 2, 1]
I\'d like to repeat each element of [a] by the number of its corresponding position
Use the zip() function with itertools.repeat() and itertools.chain.from_iterable():
try:
# use iterator zip on Python 2 too
from future_builtins import zip
except ImportError:
pass
from itertools import repeat, chain
list(chain.from_iterable(repeat(value, count) for value, count in zip(a, b)))
(I added a Python 2 forward-compatible import for those that can't switch to Python 3 yet).
Demo:
>>> from itertools import repeat, chain
>>> a = [0, 5, 1]
>>> b = [1, 2, 1]
>>> list(chain.from_iterable(repeat(value, count) for value, count in zip(a, b)))
[0, 5, 5, 1]
An alternative approach would be to use a list comprehension; this is slower as repeating elements is done in bytecode instead of C:
[value for value, count in zip(a, b) for _ in range(count)]