Common elements comparison between 2 lists
Clash Royale CLAN TAG#URR8PPP
Common elements comparison 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)
Got that so far, but can't seem to get it to work!
Any ideas?
13 Answers
13
>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]
+1 but personally I'd used frozenset as it's immutable and so can be used as dictionary key etc
– zebrabox
May 19 '10 at 11:04
This will return the /unique/ common elements, but not any repeated elements that may exist.
– Dologan
Mar 20 '14 at 18:52
@SilentGhost. How to get the number of matched elements from two list. In this case it is 2.
– Poka
Dec 9 '17 at 11:53
@Poka len(list(set(list1).intersection(list2)))
– Dharmanshu Kamra
Jan 4 at 1:38
@ Dharmanshu Kamra . Thanks a lot
– Poka
Jan 4 at 15:04
You can also use sets and get the commonalities in one line: subtract the set containing the differences from one of the sets.
A = [1,2,3,4]
B = [2,4,7,8]
commonalities = set(A) - (set(A) - set(B))
The solutions suggested by S.Mark and SilentGhost generally tell you how it should be done in a Pythonic way, but I thought you might also benefit from knowing why your solution doesn't work. The problem is that as soon as you find the first common element in the two lists, you return that single element only. Your solution could be fixed by creating a result
list and collecting the common elements in that list:
result
def common_elements(list1, list2):
result =
for element in list1:
if element in list2:
result.append(element)
return result
An even shorter version using list comprehensions:
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 of doing this -- Python's built-in set types are way more efficient as they are implemented in C internally.
Great for both proposals
– dlewin
Sep 21 '15 at 12:41
NOTE: The above methods will only work for equal sized lists. If you are working with unequal sized lists, as I am, then you will need to evaluate the order based on len() prior to calling the function: list1 = [2,2,2], list2[2,3] -> [2,2,2] list1 = [2,3], list2[2,2,2] -> [2]
– redthumb
Sep 30 '16 at 11:56
use set intersections, set(list1) & 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']
>>>
>>>
Note that result list could be different order with original list.
Thanks for the help. Understand where I went wrong and what to work on next time. :)
– Daniel
May 19 '10 at 12:29
Thats great, Daniel :-)
– YOU
May 19 '10 at 12:47
great solution. is there also a way to preserve the order with this?
– tarrasch
Aug 30 '12 at 15:47
The previous answers all work to find the unique common elements, but will fail to account for repeated items in the lists. If you want the common elements to appear in the same number as they are found in common on the lists, you can use the following one-liner:
l2, common = l2[:], [ e for e in l1 if e in l2 and (l2.pop(l2.index(e)) or True)]
The or True
part is only necessary if you expect any elements to evaluate to False
.
or True
False
Awesome solution, seems the most thorough, if a bit terse
– Hendeca
Mar 8 '17 at 21:25
This should be the answer that should have been selected! I am assuming it also works for unequal lists. Also most of the solutions use
set
which is not stable (aka the order is lost).– lifebalance
Jun 15 '17 at 14:14
set
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]
Hi, this is my propose (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) Method1
saving list1 is dictionary and then iterating each elem 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 set
def findarrayset(a,b):
common = set(a)&set(b)
diff=set(a)^set(b)
print list(common)
print list(diff)
Here's a rather brute force method that I came up with. It's certainly not the most efficient but it's something.
The problem I found with some of the solutions here is that either it doesn't give repeated elements or it doesn't 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
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)
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)
Please add some comments with your answers.
– cosmoonot
Apr 4 at 18:00
This is going to be so slow, it's better to use generated list such as
[i for i in x if i in y]
.– maf88_
May 14 at 21:20
[i for i in x if i in y]
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")
list_1=[1,2,3,4,5,3,7,8,9,10]
list_2=[1,3,3,5,11,3,234,212]
len_list1=len(list_1)
len_list2=len(list_2)
n=min(len_list1,len_list2)
final_list=
for i in range(0,n):
if(list_1[i]==list_2[i]):
final_list.append(list_1[i])
print(final_list)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Hi, could you add some details on how you plan to use the code? If this is to complete an assignment, it may be better to choose a solution which encapsulates the "Pythonic" way. However, if efficiency is your concern, then the "Pythonic" way is unlikely to be the most efficient solution. Advising us on these details will help solutions aim to solve your problem.
– Matthew Cliatt
May 15 at 2:12