2

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?

Mawg says reinstate Monica
  • 36,598
  • 98
  • 292
  • 531

1 Answers1

5

You can improve on it using enumerate():

for i, item in enumerate(list):
    if i == len(list) - 1:
        <do something>
    else:
        <do something else>
LeopardShark
  • 2,550
  • 2
  • 16
  • 30