I have this list:
a=[7086, 4914, 1321, 1887, 7060]
. Now, I want to create duplicate of each value n-times. Such as:
n=2a=[7086,7086,4914,4914,1321,1321,7060,7060]
How would I do this best? I tried a loop but it was inefficient.
I have this list:
a=[7086, 4914, 1321, 1887, 7060]
. Now, I want to create duplicate of each value n-times. Such as:
n=2a=[7086,7086,4914,4914,1321,1321,7060,7060]
How would I do this best? I tried a loop but it was inefficient.
The idiomatic way in Python is to use zip and then flatten the resulting list of tuples.
As stated in the docs:
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).
So in this case:
>>> a=[7086, 4914, 1321, 1887, 7060]
>>> n=2
>>> [e for t in zip(*[a]*n) for e in t]
[7086, 7086, 4914, 4914, 1321, 1321, 1887, 1887, 7060, 7060]
Alternatively, just flatten a constructed list of sublists made [list_item]*n
like so:
>>> [e for sl in ([e]*n for e in a) for e in sl]
# same output
Which can then be constructed as a generator which is as efficient as possible here:
>>> it=(e for sl in ([e]*n for e in a) for e in sl)
>>> next(it)
7086
>>> next(it)
7086
>>> next(it)
4914
>>> ...