Best way to extend a list with itself N times

Viewed 2256

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)
4 Answers

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.

you could use list multiplication as for the complexity, it is very fast:

s = ['a', 'b', 'c'] * i

and then you can modify elements by index, pretty nett don't you think?

To start with, if one has a list = [a, b, c], if one prints it, one will get the following error

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-17-eb02c90df247> in <module>
----> 1 list = [a, b, c]
      2 list

NameError: name 'c' is not defined

The list should be defined as follows

>>> list = ['a', 'b', 'c']
>>> print(list)
['a', 'b', 'c']

For your case, simply multiplying the list with N will do the work. For the examples, let's consider N=3

>>> n = 3
>>> list = list*n
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

Now, and giving an alternative answer, as the need may arise, if one wants to extend the list (considering, for the example, N=3) as follows

['a' 'a' 'a' 'b' 'b' 'b' 'c' 'c' 'c']

One can use np.repeat do that

>>> n = 3
>>> list= np.repeat(list, n)
array(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], dtype='<U1')

This retrieved an array. If that doesn't fit one's needs and one wants a list (use np.ndarray.tolist), as follows

>>> list = list.tolist()
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']
Related