Pythonic way to detect final iteration of a loop

Question:

Currently, I do something like

count = 0
for item in list:
  if count == len(list) - 1:
      <do something>
   else:
      <do something else>
   count += 1

Is there a more Pythonic way to recognize the final iteration of a loop – for both lists and dictionaries?

Answers:

You can improve on it using enumerate():

for i, item in enumerate(list):
    if i == len(list) - 1:
        <do something>
    else:
        <do something else>
Answered By: LeopardShark
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.