-1

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)]
karolius
  • 9
  • 3
  • 1
    Can you explain better , like what exactly you want to do ? – White Shadow Jun 08 '16 at 18:27
  • `[[i, i] for i in range(5)]`. But you could do `list(map(lambda i: [i, i], range(5)))` as well. – CodenameLambda Jun 08 '16 at 18:28
  • *But i have no idea how to do it.*, do what? –  Jun 08 '16 at 18:28
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. [See: How to create a Minimal, Complete, and Verifiable example.](http://stackoverflow.com/help/mcve) –  Jun 08 '16 at 18:29

5 Answers5

1

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.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
0

Here is one way with zip:

[i for p in zip(range(5), range(5)) for i in p]
Ringil
  • 6,277
  • 2
  • 23
  • 37
0

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)]
Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • Why it produces two values at one division operation? – karolius Jun 08 '16 at 18:33
  • It doesn't make two values at once, just one. But the floor division means we get the same value twice in a row. For instance, `0 // 2` and `1 // 2` are both `0`. – Blckknght Jun 08 '16 at 18:42
0

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.

Vasif
  • 1,393
  • 10
  • 26
0

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]
jacob
  • 4,656
  • 1
  • 23
  • 32