3

My array is [A,B,C] and I want to multiply it so I can make the array [A,A,A,B,B,B,C,C,C]

BobelLegend
  • 91
  • 2
  • 10

6 Answers6

4

you can chain the results of itertools.repeat:

import itertools
list(itertools.chain.from_iterable(itertools.repeat(x,3) for x in ["A","B","C"]))

result:

['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']

this solution minimizes the loops & the temporary lists (none is created)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
4

Use zip

>>> l = ['A','B','C']
>>> [e for sl in zip(*[l]*3) for e in sl]
['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']

Or you can use itertools.chain to flatten the list produced by zip

>>> list(chain(*zip(*[l]*3)))
['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
Sunitha
  • 11,777
  • 2
  • 20
  • 23
3

If not opposed to numpy, you can create an array of your original list repeated using np.repeat:

>>> import numpy as np
>>> np.repeat(['A','B','C'], 3)
array(['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
      dtype='<U1')

If so desired, you can convert that back to a list as opposed to an np.array using tolist:

>>> np.repeat(['A','B','C'], 3).tolist()
['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
sacuL
  • 49,704
  • 8
  • 81
  • 106
2

You could make use of list comprehensions:

>>> [item for item in ['A', 'B', 'C'] for _ in range(3)]
['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
2

Not quite as clean as the other answers, but this should work too:

test = ['A','B','C']

def repeat_elements(currentArray, numRepeat):
    newArray = []
    for elem in currentArray:
        for x in range(numRepeat):
            newArray.append(elem)

    return newArray

print repeat_elements(test, 3)
Jon Warren
  • 857
  • 6
  • 18
1

This should work for you regardless of how long the list is.

array = ['A','B','C']
new_array = []
for i in array:
    new_array += i * 3

(This works as long as you're not using integers in place of characters/strings as array elements)

Dylan Smith
  • 118
  • 1
  • 10