0

I need to form the if else condition in my code. I am comparing two list with each other and print if there is any different item in each list or there isn't any. My code is below.

title_check = [[y for y in xml_title_list if y not in json_title_list], [y for y in json_title_list if y not in xml_title_list]]
if len(title_check [0]):
    print("Type which are unmatched in XML are ", title_check [0])

if len(title_check [1]):
    print("Type which are unmatched in JSON are ", type_check[1])

else:
    print("No Unmatched type found") 

I want to combine both if conditions and want to run it every time. if they don't execute i want else then. Right now it is only taking else condition for second if condition. Can someone help me? Thanks in advance

0

3 Answers 3

1

You can use a flag as shown in the other answer. Another way to do this is

if len(title_check[0]) or len(title_check[1]):
    if len(title_check[0]):
        print("Type which are unmatched in XML are ", type_check[0])

    if len(title_check[1]):
        print("Type which are unmatched in JSON are ", type_check[1])
else:
    print("No Unmatched type found") 
Sign up to request clarification or add additional context in comments.

Comments

1

You can use set.difference:

xml, json = set(xml_title_list), set(json_title_list)
umatched_xml = json - xml
unmatched_json = xml - json

if umatched_xml or unmatched_json:
    if umatched_xml:
        print("Type which are unmatched in XML are ", umatched_xml)
    if umatched_json:
        print("Type which are unmatched in JSON are ", umatched_json)
else:
    print("No unmatched type found") 

1 Comment

Although i have found the answer but your approach is good. Still it need to address my question that what if both if conditions are false and i have to print something like "there are no unmatched types", where would i put the else condition?
0
title_check = [[y for y in xml_title_list if y not in json_title_list], [y for y in json_title_list if y not in xml_title_list]]

is_xml = False    
if len(type_check[0]):
    is_xml = True
    print("Type which are unmatched in XML are ", type_check[0])

is_json = False    
if len(type_check[1]):
    is_json = True
    print("Type which are unmatched in JSON are ", type_check[1])

if (not is_xml) and (not is_json):
    print("No Unmatched type found") 

2 Comments

You can do this with a single boolean
True @Sanketh but we don't know if xml and json are all the types that the OP needs to take care of so I've preferred a more modular / expandable approach.

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.