0

I am using a for-loop within another for-loop to iterate through and compare two data sets. I want to first use the inner for loop to check for a condition and then, if it fails, to print a value from the outer loop.

For example:

for (i) in list_one:

    for (j) in list_two:
        
        if (condition):

            print(j)

if the condition for 'print(j)' fails for all instances in list_two, I want the current value of list_one to be printed. Something like an 'if: for:' statement seems like it would make sense but I'm not sure if those are possible in Python. Thanks for the help

2
  • can you share the output/error you are getting now? Commented Mar 14, 2022 at 6:53
  • If the condition is true for some j, do you want to continue checking/printing the remaining js? Commented Mar 14, 2022 at 7:00

2 Answers 2

2

You can just add a fail flag, like

for (i) in list_one:
    fail = True
    for (j) in list_two:
        if (condition):
            fail = False
            print(j)
    if fail:
        print(i)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That worked perfectly. I will accept the answer in 4 minutes when stack overflow allows me to
0

If you need to print only the first satisfy condition and then break out of the loop, then you can use for ... else

for (i) in list_one:
    for (j) in list_two:
        if (condition):
            print(j)
            break
    else:
        print(i)

If you want to print all the values which satisfy the condition in inner loop, you can use one more variable

for (i) in list_one:
    print_i = True
    for (j) in list_two:
        if (condition):
            print(j)
            print_i = False
    if print_i:
        print(i)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.