I have a loop that is parsing lines of a text file:
for line in file:
if line.startswith('TK'):
for item in line.split():
if item.startwith('ID='):
*stuff*
if last_iteration_of_loop
*stuff*
I need to do a few assignments, but I can’t do them until the last iteration of the second for loop. Is there a way to detect this or to know if I’m at the last item of line.split()? As a note, the items in the second for loop are strings, and their content are unknown at runtime, so I can’t look for a specific string as flag to let me know I’m at the end of the list.
Just refer to the last line outside the for loop:
The
itemvariable is still available outside the for loop:Note that if your file is empty (no iterations through the loop)
itemwill not be set; this is why we setitem = Nonebefore the loop and test forif item is not Noneafterwards.If you must have the last item that matched your test, store that in a new variable:
Demonstration of the second option: