Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform an operation during the last iteration of a for loop in Python

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.

like image 989
zakparks31191 Avatar asked Nov 29 '25 10:11

zakparks31191


1 Answers

Just refer to the last line outside the for loop:

for line in file:
    if line.startswith('TK'):
        item = None
        for item in line.split():
            if item.startwith('ID='):
                # *stuff*

        if item is not None:
            # *stuff*

The item variable is still available outside the for loop:

>>> for i in range(5):
...     print i
... 
0
1
2
3
4
>>>  print 'last:', i
last: 4

Note that if your file is empty (no iterations through the loop) item will not be set; this is why we set item = None before the loop and test for if item is not None afterwards.

If you must have the last item that matched your test, store that in a new variable:

for line in file:
    if line.startswith('TK'):
        lastitem = None
        for item in line.split():
            if item.startwith('ID='):
                lastitem = item
                # *stuff*

        if lastitem is not None:
             # *stuff*

Demonstration of the second option:

>>> lasti = None
>>> for i in range(5):
...     if i % 2 == 0:
...         lasti = i
...
>>> lasti
4
like image 159
Martijn Pieters Avatar answered Dec 02 '25 00:12

Martijn Pieters