I want to make a list comprehension with duplicated values at one loop cycle like this:
s=[]
for i in range(5):
s+=[i,i]
But this doesnt work.
[i, i for i in range(5)]
I want to make a list comprehension with duplicated values at one loop cycle like this:
s=[]
for i in range(5):
s+=[i,i]
But this doesnt work.
[i, i for i in range(5)]
You can do it like this:
[i for i in range(5) for j in range(2)]
The output is:
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
The i
loop provides the values, and the j
loop serves to repeat those values.
There's no direct way to use a single level list comprehension to do exactly the same thing you're doing with your explicit loop. That's because each iteration of the loop in a comprehension must produce at most one value (it can produce zero if you have an if
clause).
However, for this specific case, you can use division to produce the sequence of repeated values you want while iterating on a larger range
:
s = [i//2 for i in range(10)]
I think this will do the trick.
[ i/2 for i in range(10)]
List comprehension will have as many elements as the iterator within the comprehension. In this case, the iterator is range(10)
Since, you need 10 elements. You will need to range over 10 and apply some computation( in this case i/2
) to get the desired element.
You may try this:
s = [[i, i] for i in range(5)]
.
And if you want it to be flattened you can try this nested list comprehension.
s = [x for y in [[i, i] for i in range(5)] for x in y]