Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
comparing 2 lists
#1
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.
Reply
#2
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]
Reply
#3
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/
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Comparing items from 2 lists of dictionaries illwill 7 871 Sep-14-2020, 10:46 PM
Last Post: bowlofred
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 1,288 Mar-20-2019, 08:01 PM
Last Post: stillsen
  Comparing values in separate lists KaleBosRatjes 3 1,723 May-02-2018, 04:38 PM
Last Post: KaleBosRatjes

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020