def list_common_elements(l_1,l_2,_unique=1,diff=0): if not diff: if _unique: return list(set(l_1)&set(l_2)) if not _unique: return list((i for i in l_1 if i in l_2)) if diff: if _unique: return list(set(l_1)^set(l_2)) if not _unique: return list((i for i in l_1 if i not in l_2)) """ Example: l_1= [0, 1, 2, 3, 3, 4, 5] l_2= [6, 7, 8, 8, 9, 5, 4, 3, 2] look for diff l_2,l_1,diff=1,_unique=1: [0, 1, 6, 7, 8, 9] sorted(unique(L_2 not in L_1) + unique(L_1 not in L_2)) l_2,l_1,diff=1,_unique=0: [6, 7, 8, 8, 9] L_2 not in L_1 l_1,l_2,diff=1,_unique=1: [0, 1, 6, 7, 8, 9] sorted(unique(L_1 not in L_2) + unique(L_2 not in L_1)) l_1,l_2,diff=1,_unique=0: [0, 1] L_1 not in L_2 look for same l_2,l_1,diff=0,_unique=1: [2, 3, 4, 5] unique(L2 in L1) l_2,l_1,diff=0,_unique=0: [5, 4, 3, 2] L2 in L1 l_1,l_2,diff=0,_unique=1: [2, 3, 4, 5] unique(L1 in L2) l_1,l_2,diff=0,_unique=0: [2, 3, 3, 4, 5] L1 in L2 """
This function allows you to compare two lists (L_1 and L_2). The DIFF parameter sets the comparison to search for common elements (DIFF == True) or various elements (DIFF == False) in both lists. At the next level, the behavior of the method is specified by the _UNIQUE parameter. _UNIQUE == True will use Python sets - in this case, the method returns a sorted list of unique elements that satisfy DIFF. When _UNIQUE == False - the returned list is more explicit, that is, first it will contain all L_1 elements, followed by all L_2 elements satisfying DIFF. Since the output will contain duplicate occurrences of elements in L_1 and L_2 that satisfy the DIFF condition, the user can count the number of times that the element is different or common to lists. Since this sentence is simply a compilation of the code proposed by "cowlinator" and JS Method2, please see these authors' publications for a discussion of the speed and performance of calculations. Cowlinator and JS Method2 Credits