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?

ledgers = Ledger.objects.all()
i = 0

for ledger in ledgers:
    print('Ledger no '+str(i)+' is '+ledger.name)
    i += 1

Advertisement

Answer

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

ledgers = Ledger.objects.all()

for i, ledger in enumerate(ledgers):
    print(f'Ledger no {i} is {ledger.name}')
Advertisement