1

I have a question where it asks me to print 10 elements consisting of 3 tuples (1,2,3)(2,3,4)....(10,11,12) using comprehension.

So far I've been able to print it in one long tuple (1,2,3,2,3,4,3,4,5,4,5,6....) with commas and no brackets separating them. The hint on the question is that only 1 for-part inside this comprehension is needed.

Input:

def try2():
  e = [x+a for x in range(0,10) for a in range (1,4)] 
  print (tuple(e))

try2()

Output:

(1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7,6, 7, 8, 7, 8, 9, 8, 9, 10, 9, 10, 11, 10, 11, 12)

Expected:

(0,1,2),(2,3,4),(3,4,5)......(10,11,12)

Actual:

(1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7,6, 7, 8, 7, 8, 9, 8, 9, 10, 9, 10, 11, 10, 11, 12)

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
snk
  • 91
  • 1
  • 8
  • Possible duplicate of [Rolling or sliding window iterator?](https://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator) – Jab Oct 14 '19 at 01:32

1 Answers1

2

You can pass the inner range generator to the tuple constructor instead:

[tuple(range(x, x + 3)) for x in range(1, 11)]

This returns:

[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10), (9, 10, 11), (10, 11, 12)]
blhsing
  • 91,368
  • 6
  • 71
  • 106