So I have a list [a,b,c] and I want to obtain [a,b,c,a,b,c,...a,b,c].
I can of course do this with two nested loops, but there must be a better way? itertools.cycle() would have been solution if I could provide a count.
Two constraints:
Eventually I came up with:
[copy.copy(e) for _ in range(N) for e in sourceList]
For immutable types, you can use multiplication operator on the list:
>>> [1,2,3]*5
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
for mutable types, you need to perform a copy of the elements prior to inserting.
I would chain a repeated copy of the items of the list.
import copy,itertools
a=[12]
b=[13]
c=[14]
l = [a,b,c]
new_l = list(itertools.chain.from_iterable(map(copy.copy,l) for _ in range(5)))
in new_l, all lists are independent (references are not copies from each other). You may need copy.deepcopy in some cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With