Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to extend a list with itself N times

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:

  1. it should work in 2.7 (but for the sake of curiosity I'm interested in a 3.x solution)
  2. list elements should be independent copies (they are mutable types)
like image 377
xenoid Avatar asked Nov 01 '25 08:11

xenoid


2 Answers

Eventually I came up with:

[copy.copy(e) for _ in range(N) for e in sourceList]
like image 87
xenoid Avatar answered Nov 03 '25 21:11

xenoid


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.

like image 20
Jean-François Fabre Avatar answered Nov 03 '25 23:11

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!