3

I have a list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] and I want to repeat a list n times.
For example, if n = 2 I want [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] as output.

Is there any inbuilt solution in python except append and for loop because value of n might go up to 1000 too ?

Gsk
  • 2,929
  • 5
  • 22
  • 29
Paras Ghai
  • 363
  • 1
  • 6
  • 14

4 Answers4

9

Python allows multiplication of lists:

my_list = [0,1,2,3,4,5,6,7,8,9]
n = 2
print(my_list*n)

OUTPUT:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Gsk
  • 2,929
  • 5
  • 22
  • 29
  • 1
    Note that this will copy objects by reference, so may lead to some very difficult to find bugs. – Mous Mar 01 '22 at 07:23
2

If the generated list is large, it can be better to use a generator, so that items are generated one at a time on the fly without creating the whole large list in memory:

from itertools import islice, cycle


def repeat(lst, times):
    return islice(cycle(lst), len(lst)*times)

lst = [0, 1, 2, 3, 4, 5]

for item in repeat(lst, 3):
    print(item, end=' ')

#0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 

You can still create a list if you want:

print(list(repeat(lst, 3)))
# [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]

How it works: itertools.cycle will cycle on lst indefinitely, and we keep only the len(lst) * times first items using itertools.islice

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
1

Just use multiplication

[1,2,3] * 3
# [1,2,3,1,2,3,1,2,3]
tomgalpin
  • 1,943
  • 1
  • 4
  • 12
1

This is how you can achieve it.

arr1=[1,2]
n=2
arr2=arr1*n #number of times you want to repeat
print(arr2)

Output:

[1,2,1,2]

Apurva Singh
  • 411
  • 3
  • 14