Search code examples
pythonenumerate

How do I get the upper bound of a for loop in Python?


I want to do the following in Python:

for index, value in enumerate(MyFunction()):
  logger.debug('Processing step %d of %d' % (index, len(MyFunction())

but that requires me to call MyFunction() during every iteration which I don't want. So of course I can do

mylist = MyFunction()
for index, value in enumerate(mylist):
  logger.debug('Processing step %d of %d' % (index, len(mylist)))

but that requires an unnecessary variable. Is there a more elegant way to refer to the maximum value of the loop index inside the for loop?


Solution

  • No. In general, there may not be a maximum index, because you could do for x in some_infinite_iterator().