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
  • 38,334
  • 103
  • 306
  • 551

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
  • 3,820
  • 2
  • 19
  • 33