Python Forum
comparing 2 lists - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: comparing 2 lists (/thread-34318.html)



comparing 2 lists - rwahdan - Jul-18-2021

Hi,

I have problem comparing 2 lists. one list has 10 records and the other have less than 10 so it is between 1 and 9 records. What I am trying to accomplish is to compare the 2 lists and create new empty list to hold the missing items. Example:

        for rec in records2:
            questions.append(rec[4])

        for record in records:
            questions2.append(record[0])
First List has list of let us say [1,3,5,6,7]
Second List has list of [1,2,3,4,5,6,7,8,9,10]
so I need to compare them and get a new list that has [2,4,8,9,10]

thanks.


RE: comparing 2 lists - Yoriz - Jul-18-2021

list_one = [1,3,5,6,7]
list_two = [1,2,3,4,5,6,7,8,9,10]
difference = set(list_two).symmetric_difference(list_one)
print(list(difference))
Output:
[2, 4, 8, 9, 10]



RE: comparing 2 lists - DeaD_EyE - Jul-18-2021

Iterative way, if order of sequence is important:

# Generator - lazy evaluated
# must be consumed after called, e.g. from list() or a for loop

def compare(exclude, sequence):
    for element in sequence:
        if element not in exclude:
            yield element


to_exclude =  [1,3,5,6,7]
sequence = [1,2,3,4,5,6,7,8,9,10]

# comsume the generator
missing_values = list(compare(to_exclude, sequence))
print(missing_values)
Output:
[2, 4, 8, 9, 10]
Or the classic way:
def compare(exclude, sequence):
    result = []
    for element in sequence:
        if element not in exclude:
            result.append(element)
    return result


to_exclude =  [1,3,5,6,7]
sequence = [1,2,3,4,5,6,7,8,9,10]

# this time a normal function which returns a list with results
missing_values = compare(to_exclude, sequence)
print(missing_values)
Output:
[2, 4, 8, 9, 10]
Another approach, if the order doesn't matter, are sets.

to_exclude =  set([1,3,5,6,7])
sequence = set([1,2,3,4,5,6,7,8,9,10])

missing_values = sequence - to_exclude
print(missing_values)
Output:
{2, 4, 8, 9, 10}
More about set: https://realpython.com/python-sets/