pythonlistdifferenceinverse

For each numbers list or (tuple) from Lists or (Tuples) get a difference from this main one list and return or store all those Lists to variable


My need is to get the list difference or inverse (NOT (reverse)) of many lists from the main list, and save those inverted lists to variable to print them to see the output.

FYI, I know how to get the difference of two list but NOT the difference of many lists. Sample code for difference between two list:

a = [1,2,3,4,5,6,7,8,9,10]
b = [2,4,6,8,10]
c = [number for number in a if number not in b]
print(c)  # OUTPUT: [1, 3, 5, 7, 9]

I get all my lists from table in database see two lines of code below:

t_numbers = cur.execute("SELECT n1, n2, n3, n4, n5 FROM Numbers")
all_list_of_numbers = [num for num in t_numbers]

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

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

I am writing a function but it doesn't work out at all the way I wanted to return me the lists. Maybe I don't need a function, maybe using a list comprehension or else something better?

def Diff(main_list, all_list_numbers):
     return list(set(main_list) - set(all_list_numbers)) + list(set(all_list_numbers) - set(main_list))

Also I have a function that checks and gets the count total five numbers from Numbers table:

def get_total_numbers(allfiveNumbers):
    count = 0
    for numbers in allfiveNumbers:
        count += 1

# print("All the number in the list: ", get_total_numbers(all_list_numbers))
# OUTPUT -- All five numbers lists is:  20

Solution

  • Here is one way:

    main_set = set(main_list)
    res = [main_set.symmetric_difference(i) for i in all_list_of_numbers]
    

    Output:

    [{6, 7, 8, 9, 10},
     {4, 6, 7, 8, 10},
     {1, 3, 5, 6, 9},
     {1, 2, 4, 7, 9},
     {1, 2, 3, 7, 10},
     {2, 4, 5, 8, 9},
     {1, 4, 5, 7, 9},
     {1, 2, 3, 4, 6},
     {3, 5, 7, 8, 10},
     {4, 5, 6, 7, 10},
     {2, 3, 4, 7, 10},
     {1, 6, 8, 9, 10},
     {2, 4, 6, 8, 9},
     {1, 3, 7, 9, 10},
     {1, 2, 4, 6, 7},
     {1, 5, 6, 8, 10},
     {1, 2, 5, 6, 8},
     {1, 2, 5, 9, 10},
     {1, 2, 3, 4, 9},
     {2, 3, 5, 8, 10}]