Nested list comprehension where inner loop range is dependent on outer loop
<p>I am trying to represent the following as a list comprehension:</p>

<pre><code>L = []
for x in range(n):
    for y in range(x):
        L.append( (x, y) )
</code></pre>

<p>I have done nested list comprehension in the more typical matrix scenario where the inner loop range is not dependent on the outer loop.</p>

<p>I have considered there may be solutions in <code>itertools</code>, using <code>product()</code> or <code>chain()</code> but have been unsuccessful there as well.</p>

<p>Below is the example to convert your code to list comprehension.</p>

<pre><code>&gt;&gt;&gt; n = 10
&gt;&gt;&gt; [ (x,y) for x in range(n) for y in range(x)]
[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (9, 0), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8)]
</code></pre>

<p><strong>Alternatively,</strong> you achieve the same result using <code>itertools</code> library (sharing it just for your knowledge info, but is not recommended for this problem statement):</p>

<pre><code>&gt;&gt;&gt; import itertools
&gt;&gt;&gt; list(itertools.chain.from_iterable(([(list(itertools.product([x], range(x)))) for x in range(n)])))
[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (9, 0), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8)]
</code></pre>

python python-3.x list-comprehension nested-loops