Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - make a list with repetitive elements

Tags:

python

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

like image 650
soroosh.strife Avatar asked Feb 13 '26 02:02

soroosh.strife


2 Answers

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.

like image 198
sashkello Avatar answered Feb 14 '26 14:02

sashkello


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]
like image 44
dersvenhesse Avatar answered Feb 14 '26 14:02

dersvenhesse