Python Forum
checking for last item in for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
checking for last item in for loop
#10
(Jul-07-2021, 10:58 AM)ibreeden Wrote: I find this the most elegant way to process the list:
the_list = [1,2,3,4]

for i in the_list[0:-1]:
    print(f"Processing {i}")

print(f"Post processing {the_list[-1]}")
Output:
Processing 1 Processing 2 Processing 3 Post processing 4

for cases where the entire body of the loop changes, i agree that is the best way. but if the last cycle needs to change only a portion, more so the smaller that portion is, i would prefer to avoid any duplicated code and have every cycle performed by the same body code that tests for the case of the last cycle. if the common part of that code ever needs to be changed or trapped for debugging, avoiding duplication makes code maintenance easier (so there is never an issue of what needs to be the same actually being the same).
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Messages In This Thread
checking for last item in for loop - by Skaperen - Jul-04-2021, 07:58 PM
RE: checking for last item in for loop - by Yoriz - Jul-04-2021, 08:42 PM
RE: checking for last item in for loop - by Skaperen - Jul-09-2021, 12:40 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Remove an item from a list contained in another item in python CompleteNewb 19 5,916 Nov-11-2021, 06:43 AM
Last Post: Gribouillis
  Iterating over a dictionary in a for loop - checking code has worked sallyjc81 1 1,964 Dec-29-2020, 05:14 PM
Last Post: ndc85430
  Checking for an item in a list (if then statement) Sailnir 1 2,093 Jul-18-2019, 05:36 PM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020