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?

5
  • 1
    Do you really need to know if its the last element? Usually you can get around this by using ', '.join(list) for example. Commented Jul 22, 2019 at 8:18
  • 3
    @T.Nel it wasn't flagged as unhelpful, it was flagged as a duplicate, which it is. Commented Jul 22, 2019 at 8:33
  • Duplicate of which? Commented Jul 22, 2019 at 8:46
  • 1
    @Mawg, it seems your first question around here... Commented Jul 22, 2019 at 9:12
  • @Mawg of the two questions linked to as duplicates at the top. Commented Jul 22, 2019 at 10:49

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

you only need to calculate last item in list once last_item = list[-1]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.