Python Forum
checking for last item in for loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: checking for last item in for loop (/thread-34179.html)

Pages: 1 2


RE: checking for last item in for loop - jefsummers - Jul-09-2021

Grab the last and use it for comparison
the_list = [1,2,3,4]
final = the_list[-1] 
for i in the_list:
    if i == final:
        print('Processing last')
    else:
        print(f"Processing {i}")
Output:
Processing 1 Processing 2 Processing 3 Processing last



RE: checking for last item in for loop - Skaperen - Jul-09-2021

what if the code that needs to be slightly changed is a function call with one of many arguments changed?