user2068804 user2068804 - 1 year ago 45
Python Question

Executing for loop with if loop inside until it's complete

I want to accomplish the following thing in my python program:

for l in list(p):
if condition1:

if condition2:
return something

What I want to do here that, is it possible to execute the for loop until it's finished and then execute the 2nd if loop only once. The thing is that the 2nd if loop has to be inside for loop and it should execute only once.

Please let me know if that's possible and how can I do it??

Answer Source

You may want to move that code block to the else block of the for loop which executes immediately after the for loop is exhausted. The second if will be executed only once:

for l in p:
    if condition1:
    if condition2:
         return something

The else block of the for will be executed provided there were no exceptions, break or return statements in the body of the for loop.

On a side note, if p is iterable, you don't need to call list on it before using it in your for