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

asked Mar 14, 2022 at 6:51
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)
answered Mar 14, 2022 at 6:57
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)
answered Mar 14, 2022 at 7:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.