Home > OS >  How to compare two lists in python with the if loc condition
How to compare two lists in python with the if loc condition

Time:12-15

I have two lists and i need to compare those two lists in below manner

import sys
name_1=['mahesh','karthik','nani','Karun']
name_2 = ['mahesh','karthik','','Karun','mari']

list_match = []
counter = 0
for i in name_2:  
    try: 
        if i in name_1:
            pass
        else:
            list_match.append(i)
            counter = counter   1

            print(f"'{list_match[0]}' is missing")
    
    except Exception as e:
        print(e)

    if counter > 0:
        sys.exit()

Output Getting:

   unnamed :3 is missing

Expected Output:

   Nani is extra column        

CodePudding user response:

first thing, you miss an equal and plus there's a void space in between two elements of the second list. Secondly, based on your script, you'll never get the expected output. That's because "Nani" is only in the first list and not in the second but, since you're iterating over the second list, you'll never get to know that Nani is only in name_1. If the task is to detect missing elements in the second list, but present in the first, you need to iterate over name_1, as it follows (I used the same style as you):

name_1 = ['mahesh','karthik','nani','Karun', 'mari']
name_2 = ['mahesh','karthik','Karun']

list_match = []
non_match = []
for i in name_1:
    try: 
        if i not in name_2:
            non_match.append(i)
            print(f"'{i}' is missing")
            break
        else:
            list_match.append(i)
    except Exception as e:
        print(e)

The program ends when it first detect a missing element. To terminate the program after every evaluation of the missing elements, comment the break instruction. I didn't quite understand the presence of the variabile non_match, and the list_match presence, as well, since you didn't use them. I also replaced the last "if statement" with a "break" in the first "if statement".

A simpler way to get missing elements it's to consider the two lists as sets and get the difference between them, as it follows:

name_1 = ['mahesh','karthik','nani','Karun', 'mari']
name_2 = ['mahesh','karthik','Karun']

name_1 = set(name_1)
name_2 = set(name_2)

print("missing elements in the second list:\n", list(name_1 - name_2))

if you invert the order of the subtraction you'll obtain the missing elements of the first list.

if the task is to obtain the elements that are missing in both list, you can try this:

name_1 = ['mahesh','karthik','nani','Karun', 'mari']
name_2 = ['mahesh','karthik','Karun', 'Aldo']

name_1 = set(name_1)
name_2 = set(name_2)

print("mismatched elements:\n", list(name_1.symmetric_difference(name_2)))

EDIT Based on the new request, here's the code:

name_1 = ['mahesh','karthik','nani','Karun']
name_2 = ['mahesh','karthik','','Karun','mari']

list_match = []

i = 0
while i < len(name_2):
    if not name_2[i]:
        print("empty element founded in position ", i)
    elif name_2[i] not in name_1:
        print(f"'{name_2[i]}' is extra column in position ", i)
        #break
    else:
        list_match.append(i)
    i =1

Output:

empty element founded in position  2
'mari' is extra column in position  4

Remove the comment from break to end the program after the first mismatch.

EDIT x2 if you want this kind of output:

empty element founded in position  2
'mari' is extra column in position  4
'nani' is extra column in position  2

and if you NECESSARLY need to use lists you can try this (but I higly reccommend to use sets instead)

name_1=['mahesh','karthik','nani','Karun']
name_2 = ['mahesh','karthik','','Karun','mari']

list_match = []

i = 0
while i < len(name_2):
    if not name_2[i]:
        print("empty element founded in position ", i)
    elif name_2[i] not in name_1:
        print(f"'{name_2[i]}' is extra column in position ", i)
        #break
    else:
        list_match.append(name_2[i])
    i =1

for el in name_1:
    if el not in list_match:
        print(f"'{el}' is extra column in position ", name_1.index(el))

Hope that was useful.

CodePudding user response:

If you're looking for the symmetric difference between two lists then ideally you'd maintain them as sets but, assuming you have a good reason not quoted here to use lists then you can do it like this:

import sys

name_1=['mahesh','karthik','nani','Karun']
name_2=['mahesh','karthik', 'Karun']

missing = set(name_1) ^ set(name_2)
print('\n'.join(f'{name} is missing' for name in missing))

if len(missing):
    sys.exit()

CodePudding user response:

I would iterate through the list you're wanting to check like so:

name_1=['mahesh','karthik','nani','Karun']
name_2 ['mahesh','karthik','Karun']

for item in name_1:
    if item not in name_2:
        print(f"{item} is missing.")

And if you'd like to add the items that are missing to a new list:

missing_items_list = []
for item in name_1:
    if item not in name_2:
        missing_items_list.append(item)
print(f"Missing items from list_2: {missing_items_list}")
  • Related