soroosh.strife
soroosh.strife

Reputation: 1191

python - make a list with repetitive elements

I know if I want to create a list like this:

[0 1 2 0 1 2 0 1 2 0 1 2]

I can use this command:

range(3) * 4

Is there a similar way to create a list like this:

[0 0 0 0 1 1 1 1 2 2 2 2]

I mean a way without loops

Upvotes: 2

Views: 897

Answers (6)

sashkello
sashkello

Reputation: 17871

Integer division can help:

[x/4 for x in range(12)]

Same thing through map:

map(lambda x: x/4, range(12))

In python 3 integer division is done with //.

Beware that multiplication of a list will likely lead to a result you probably don't expect.

Upvotes: 7

Nigel Tufnel
Nigel Tufnel

Reputation: 11524

itertools module is always an option:

>>> from itertools import chain, repeat
>>> list(chain(repeat(0, 4), repeat(1, 4), repeat(2, 4)))
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]

More general way is:

def done(group_count, repeat_count):
    return list(chain(*map(lambda i: repeat(i, repeat_count),
                           range(group_count))))
>>> done(3, 4)
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]

Upvotes: 3

UltraInstinct
UltraInstinct

Reputation: 44444

Without any explicit "for" :)

>>> list(chain(*zip(*([range(5)] * 5))))
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]

Upvotes: 3

AlanF
AlanF

Reputation: 25

If you can't use a loop in your current method, create one in an other?

range(0,1)*4 + range(1,2)*4 + range(2,3)*4

Upvotes: 0

dersvenhesse
dersvenhesse

Reputation: 6404

Yes, you can.

>>> [e for e in range(3) for _ in [0]*4]
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]

Upvotes: 6

James Sapam
James Sapam

Reputation: 16940

What about this:

>>> sum([ [x]*4 for x in range(5)],[])
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
>>>

or

>>> reduce(lambda x,y: x+y, [ [x]*4 for x in range(5)])
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
>>>

Upvotes: 1

Related Questions