Skip to content
Advertisement

What’s the cleanest way of counting the iteration of a queryset loop?

I need to loop through a queryset and put the objects into a dictionary along with the sequence number, i, in which they appear in the queryset. However a Python for loop doesn’t seem to provide a sequence number. Therefore I’ve had to create my own variable i and increment it with each loop. I’ve done something similar to this, is this the cleanest solution?

JavaScript

Advertisement

Answer

enumerate(…) [Python-doc] is designed for that:

JavaScript
Advertisement