2

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

soroosh.strife
  • 1,181
  • 4
  • 19
  • 45

6 Answers6

7

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.

Community
  • 1
  • 1
sashkello
  • 17,306
  • 24
  • 81
  • 109
6

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]
dersvenhesse
  • 6,276
  • 2
  • 32
  • 53
3

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]
Nigel Tufnel
  • 11,146
  • 4
  • 35
  • 31
3

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]
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
1

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]
>>>
James Sapam
  • 16,036
  • 12
  • 50
  • 73
0

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
dersvenhesse
  • 6,276
  • 2
  • 32
  • 53
AlanF
  • 25
  • 4