Maintain count in python list comprehension
<p>In Python, is there any <code>counter</code> available during the list comprehension as it would be in case of a <code>for</code> loop?</p>

<p>It would be more clear why I need a counter, with this example:</p>

<p>I wish to achieve the following:</p>

<p>Initial List: <code>['p', 'q', 'r', 's']</code></p>

<p>Desired List: <code>[(1, 'P'), (2, 'Q'), (3, 'R'), (4, 'S')]</code></p>

<p>In the desired list, first element of every tuple are ordinal numbers. If it were just flat list, I could have used <code>zip</code> to achieve this. But however, the list I am dealing with is nested, three level deep (think of hierarchical data), and it is generated through list comprehension.</p>

<p>So, I was wondering is there any way to introduce those ordinal numbers during list comprehension. If not, what would be the best possible solution.</p>

<p>P.S. : Here the lower case letters are converted to uppercase, but that is not a part of problem, think of it as just a data conversion.</p>

<p>Code:</p>

<pre><code>allObj = Category.objects.all()

tree =[(_, l1.name, [(__, l2.name, [(___, l3.name) for l3 in allObj if l3.parentid == l2.categoryid]) for l2 in allObj if l2.parentid == l1.categoryid]) for l1 in allObj if l1.parentid == None]
</code></pre>

<p><code>allObj</code> contains data from table category, which in turn contains hierarchical data represented in the form of Adjacency List.</p>

<p>I have put <code>_</code> where I need ordinal numbers to be. Notice that the list is nested, so there will be a separate counter at each level represented by 1, 2 &amp; 3 <code>_</code>s.</p>
