views:

113

answers:

6

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?

+6  A: 
[y for x in range(3) for y in [x, x]]
Ignacio Vazquez-Abrams
If one wants to generatlize it one could write `[x]*2` instead of `[x,x]`.
phimuemue
@phimuemue: which would be even slower
SilentGhost
+2  A: 
>>> [int(x/2) for x in range(6)]
[0, 0, 1, 1, 2, 2]
Ned Batchelder
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
A: 

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
`math.floor()` returns a `float`, so this is not quite the same.
Ignacio Vazquez-Abrams
returns integer in py3k, though
SilentGhost
+1  A: 
>>> [i for i in range(3) for _ in range(2)]
[0, 0, 1, 1, 2, 2]
SilentGhost
+2  A: 

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
A: 
[x/2 for x in range(6)]

update:

[x//2 for x in range(6)] #ok now ?
singularity
just for python 2.x...
Ant
yeap that right :)
singularity
@Ant: change to py3k syntax is trivial. However the same solution was given by Ned
SilentGhost
@silent ghost and why it's trivial? write x//2 it's better, in my opinion...
Ant
@ant: change is trivial.
SilentGhost