Skip to content Skip to sidebar Skip to footer

Repeating List In Python N Times?

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 outpu

Solution 1:

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]

Solution 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


defrepeat(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

Solution 3:

Just use multiplication

[1,2,3] * 3# [1,2,3,1,2,3,1,2,3]

Solution 4:

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]

Post a Comment for "Repeating List In Python N Times?"