Comparing common items between 2 lists

def common_elements(list1, list2): """ Return a list containing the elements which are in both list1 and list2 >>> common_elements([1,2,3,4,5,6], [3,5,7,9]) [3, 5] >>> common_elements(['this','this','n','that'],['this','not','that','that']) ['this', 'that'] """ for element in list1: if element in list2: return list(element) 

So far, but can't make it work!

Any ideas?

+104
python list
May 19 '10 at 10:57
source share
19 answers
 >>> list1 = [1,2,3,4,5,6] >>> list2 = [3, 5, 7, 9] >>> list(set(list1).intersection(list2)) [3, 5] 
+204
May 19 '10 at 11:00
source share

You can also use sets and get similarities in one line: subtract a set containing differences from one of the sets.

 A = [1,2,3,4] B = [2,4,7,8] commonalities = set(A) - (set(A) - set(B)) 
+40
Jul 22 '16 at 23:17
source share

The solutions offered by S.Mark and SilentGhost usually tell you how to do this in Pythonic, but I thought you could also find out why your solution doesn't work. The problem is that as soon as you find the first common item in two lists, you return only that single item. Your solution can be eliminated by creating a result list and collecting common elements in this list:

 def common_elements(list1, list2): result = [] for element in list1: if element in list2: result.append(element) return result 

An even shorter version using lists:

 def common_elements(list1, list2): return [element for element in list1 if element in list2] 

However, as I said, this is a very inefficient way to do this - the Python built-in types are more efficient because they are implemented inside C inside.

+32
May 19 '10 at 11:30 a.m.
source share

use multiple intersections, set (list1) and set (list2)

 >>> def common_elements(list1, list2): ... return list(set(list1) & set(list2)) ... >>> >>> common_elements([1,2,3,4,5,6], [3,5,7,9]) [3, 5] >>> >>> common_elements(['this','this','n','that'],['this','not','that','that']) ['this', 'that'] >>> >>> 

Please note that the list of results may differ from the original list.

+26
May 19 '10 at 11:00
source share

You can use a simple list comprehension:

 x=[1,2,3,4] y=[3,4,5] common = [i for i in x if i in y] common: [3,4] 
+11
Mar 28 '18 at 19:13
source share

In previous answers, everyone works to find unique common items, but will not take into account duplicate items in lists. If you want the common elements to be displayed in the same amount as in the general lists, you can use the following single-line font:

 l2, common = l2[:], [ e for e in l1 if e in l2 and (l2.pop(l2.index(e)) or True)] 

The or True is only necessary if you expect any elements to be evaluated using False .

+10
Mar 20 '14 at 18:49
source share

this is my suggestion, I think with sets is easier than with a for loop

 def unique_common_items(list1, list2): # Produce the set of *unique* common items in two lists. return list(set(list1) & set(list2)) 
+6
Oct. 16 '18 at 9:49
source share

Seth is another way to solve this problem.

 a = [3,2,4] b = [2,3,5] set(a)&set(b) {2, 3} 
+5
Nov 25 '18 at 19:08
source share

1) Method1, preserving list1, is a dictionary, and then iterates over each item in list2.

 def findarrayhash(a,b): h1={k:1 for k in a} for val in b: if val in h1: print("common found",val) del h1[val] else: print("different found",val) for key in h1.iterkeys(): print ("different found",key) 

Finding common and different elements:

2) Method2 using a set

 def findarrayset(a,b): common = set(a)&set(b) diff=set(a)^set(b) print list(common) print list(diff) 
+2
Aug 12 '15 at 20:57
source share

Use a generator:

 common = (x for x in list1 if x in list2) 

The advantage here is that it will return in constant time (almost instantly) even when using huge lists or other huge iterations.

For example,

 list1 = list(range(0,10000000)) list2=list(range(1000,20000000)) common = (x for x in list1 if x in list2) 

All other answers here will take a lot of time with these values ​​for list1 and list2.

Then you can repeat the answer with

 for i in common: print(i) 
+2
Mar 27 '19 at 20:02
source share

Here is a pretty crude method that I came across. This, of course, is not the most effective, but it is something.

The problem I found with some of the solutions here is that it either does not give duplicate elements or does not give the correct number of elements when the input order matters.

 #finds common elements def common(list1, list2): result = [] intersect = list(set(list1).intersection(list2)) #using the intersection, find the min count1 = 0 count2 = 0 for i in intersect: for j in list1: if i == j: count1 += 1 for k in list2: if i == k: count2 += 1 minCount = min(count2,count1) count1 = 0 count2 = 0 #append common factor that many times for j in range(minCount): result.append(i) return result 
+1
Jan 27 '16 at 16:39
source share
 a_list = range(1,10) b_list = range(5, 25) both = [] for i in b_list: for j in a_list: if i == j: both.append(i) 
+1
Apr 04 '18 at 17:34
source share
 f_list=[1,2,3,4,5] # First list s_list=[3,4,5,6,7,8] # Second list # An empty list stores the common elements present in both the list common_elements=[] for i in f_list: # checking if each element of first list exists in second list if i in s_list: #if so add it in common elements list common_elements.append(i) print(common_elements) 
+1
Apr 18 '18 at 6:12
source share

Hi, this is my suggestion (very simple)

 import random i = [1,4,10,22,44,6,12] #first random list, could be change in the future j = [1,4,10,8,15,14] #second random list, could be change in the future for x in i: if x in j: #for any item 'x' from collection 'i', find the same item in collection of 'j' print(x) # print out the results 
+1
Jul 22 '18 at 22:27
source share
 def common_member(a, b): a_set = set(a) b_set = set(b) if (a_set & b_set): print(a_set & b_set) else: print("No common elements") 
+1
Sep 09 '18 at 13:10
source share
 list_1=range(0,100) list_2=range(0,100,5) final_list=[] for i in list_1: for j in list_2: if i==j: final_list.append(i) print(set(final_list)) 
+1
Sep 15 '18 at 8:49
source share

Your problem is that you are returning from a for loop, so you only get the first match. The solution is to move your return out of the loop.

 def elementosEnComunEntre(lista1,lista2): elementosEnComun = set() for e1 in lista1: if(e1 in lista2): elementosEnComun.add(e1) return list(elementosEnComun) 
+1
Nov 29 '18 at 20:17
source share
 import numpy as np np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1]) array([1, 3]) 
0
Feb 03 '19 at 3:32
source share
 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

0
Aug 12 '19 at 15:20
source share



All Articles