Fabian Bosler
Fabian Bosler

Reputation: 2510

Extend list by repeating individual elements in python

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]

Upvotes: 4

Views: 967

Answers (7)

DirtyBit
DirtyBit

Reputation: 16772

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]

Upvotes: 4

Sachin
Sachin

Reputation: 61

You can use.

lst = []
repetitions = 3
for elem in range(2):
   for _ in range(elem+1):
       lst.append(elem)

This should be faster than adding lists.

Upvotes: 0

Acohen
Acohen

Reputation: 36

print([ i for i in range(3) for j in range(3)])

Try this, this is nested list comprehension, and just one lines pretty much what you do there.

Upvotes: 0

Masklinn
Masklinn

Reputation: 42292

I don't know about easier, but itertools has repeat, so

lst = [r for e in <items to repeat> for r in repeat(e, repetitions)

or

lst = list(chain.from_iterable(repeat(e, repetitions) for e in <items to repeat>)

Upvotes: 0

pault
pault

Reputation: 43504

One solution using itertools.chain

from itertools import chain
print(list(chain.from_iterable(([x]*3 for x in [0,1,2]))))
#[0, 0, 0, 1, 1, 1, 2, 2, 2]

Upvotes: 0

Netwave
Netwave

Reputation: 42708

itertools is your friend:

>>> list(itertools.chain.from_iterable(itertools.repeat(i, 3) for i in range(1, 4)))
[1, 1, 1, 2, 2, 2, 3, 3, 3]

Upvotes: 1

Aran-Fey
Aran-Fey

Reputation: 43166

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]

Upvotes: 5

Related Questions