1

I'm trying to create a list of pairs, p, from 2 ranges,

r1 = [i for i in range(0, 10, 2)]
r2 = [j for j in range(10, 0,-2)]

Such that,

p[0] = [r1[0], r2[1]]
p[1] = [r1[1], r2[1]]
.....
p[-1] = [r1[-1], r2[-1]]

Naively I thought,

p = [[i, j] for i in range(0, 10, 2) for j in range(10, 0, -2)]

would do this but I soon saw the error of my ways.

I also tried,

p = [r1[:], r2[:]]

but yeah that didn't work either.

Then I tried,

p = []
for i, j  in zip(r1, r2):
    p.append([i, j]) 

Which does work!

But that got me wondering, is there a Pythonic way of doing this using list comprehensions?

The 2 ranges will always be the same length in implementation but not always spanning the same domain.

EDIT: to be clear I was wondering if it was possible to generate the ranges r1 & r2 within the comprehension as well as the comprehension giving the pairing.

DrBwts
  • 3,470
  • 6
  • 38
  • 62

1 Answers1

1

Converting to list comprehension for the one that works as mentioned in code you posted above, may be you can try:

[[i,j] for i, j  in zip(r1, r2)]

Or to add range in list comprehension:

[[i,j] for i, j  in zip(range(0, 10, 2), range(10, 0, -2))]
niraj
  • 17,498
  • 4
  • 33
  • 48