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>
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?
You can improve on it using enumerate()
:
for i, item in enumerate(list):
if i == len(list) - 1:
<do something>
else:
<do something else>