16

I have this list comprehension:

[[x,x] for x in range(3)]

which results in this list:

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

but what I want is this list:

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

What's the easiest to way to generate this list?

Colin
  • 10,447
  • 11
  • 46
  • 54

7 Answers7

16
[y for x in range(3) for y in [x, x]]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
5
>>> [i for i in range(3) for _ in range(2)]
[0, 0, 1, 1, 2, 2]
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
5

a general solution;

m = 3   #the list of integers
n = 2   # of repetitions
[x for x in range(m) for y in range(n)]
joaquin
  • 82,968
  • 29
  • 138
  • 152
2
>>> [int(x/2) for x in range(6)]
[0, 0, 1, 1, 2, 2]
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • Maybe using the integer division operator with `x // 2` would be better than `int(x / 2)`? In Python 2.7, `timeit` shows `//` to be a little more than twice as fast, In Python 3.1, nearly three times, for large ranges. – gotgenes Oct 13 '10 at 19:26
1

My solution:

def explode_list(p,n):
    arr=[]
    track=0

    if n==0:
        return arr    
    while track<len(p): 
        m=1
        while m<=n:
            arr.append(p[track])
            m=m+1
        track=track+1

    return arr
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
khurram
  • 11
  • 1
0

You might get away with this:

[floor(x/2) for x in range(6)]

edit1

[int(x/2) for x in range(6)]

is the more portable solution in the same vein. Although the other presented answers seem better.

JoshD
  • 12,490
  • 3
  • 42
  • 53
0
[x/2 for x in range(6)]

update:

[x//2 for x in range(6)] #ok now ?
mouad
  • 67,571
  • 18
  • 114
  • 106