Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend list by repeating individual elements in python

Tags:

python

list

Is there an easier way to achieve the below?

lst = []
repetitions = 3
for elem in range(3):
    lst  += [elem] * repetitions

this turns [0,1,2] into [0,0,0,1,1,1,2,2,2]

like image 235
Fabian Bosler Avatar asked Nov 05 '25 04:11

Fabian Bosler


2 Answers

You could use a list comprehension with two loops:

>>> [elem for elem in range(3) for _ in range(repetitions)]
[0, 0, 0, 1, 1, 1, 2, 2, 2]
like image 104
Aran-Fey Avatar answered Nov 08 '25 01:11

Aran-Fey


Using list comprehension:

print([item for item in lst for i in range(3)])

Using numpy.repeat:

lst = [0,1,2]
print(list(np.repeat(lst,3)))

OUTPUT:

[0, 0, 0, 1, 1, 1, 2, 2, 2]
[0, 0, 0, 1, 1, 1, 2, 2, 2]
like image 43
DirtyBit Avatar answered Nov 08 '25 00:11

DirtyBit