# Python find common elements in two lists

1 vote
74 views

## Problem:

I am new to programming language. I was trying to find common elements in two lists using python. So I wrote this code:
a = [1, 2, 6, 9]
b = [1, 3, 8, 9]

a_as_set = set(b)
intersection =a_as_set.intersection(b)

intersection_as_list = list(intersection)

print(intersection_as_list)

This code gives me the output:

[8, 1, 3, 9]

1 vote

Main error of your code is caused by the line:
a_as_set = set(b)

If you put a list of ain a list of b it will not compare but it will take each of its elements to show.

So your code should be like:

a = [1, 2, 6, 9]
b = [1, 3, 8, 9]
a_as_set = set(a)
intersection =a_as_set.intersection(b)
intersection_as_list = list(intersection)
print(intersection_as_list)

And its output will be:

[1, 9]

## Solution:

>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]

You can further exercise sets and obtain the commonalities in one line: deduct the set bearing 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 revealed by S.Mark and SilentGhost originally inform you how it must be done in a Pythonic methos, however I conceived you might further convenienced from knowing why your solution doesn't work. The issue is that as soon as you trace the first common element in the two lists, you return that single element only. Your solution could be fixed by making a result list and collecting the usual elements in that list:

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

An in fact shorter version exercising list comprehensions:

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

But, as I said, this is a very inefficient method of doing this -- Python's built-in set types are way more efficient as they are accomplished in C internally.

Employ 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 diverse order with original list.

you can exercise a easy list comprehension:

x=[1,2,3,4]
y=[3,4,5]
common = [i for i in x if i in y]
common: [3,4]

Set is another method we can solve this

a = [3,2,4]
b = [2,3,5]
set(a)&set(b)
{2, 3}

The former answers all perform to trace the unique usual elements, however will fail to account for repeated items in the lists. In case you want the usual elements to seem in the same number as they are found in common on the lists, you can employ 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 just required in case you expect any elements to evaluate to False.

I compared each of system that each answer mentioned. At this moment I employ python 3.6.3 for this accomplishment. This is the code that I have exercised:

import time
import random
from decimal import Decimal

def method1():
common_elements = [x for x in li1_temp if x in li2_temp]
print(len(common_elements))

def method2():
common_elements = (x for x in li1_temp if x in li2_temp)
print(len(list(common_elements)))

def method3():
common_elements = set(li1_temp) & set(li2_temp)
print(len(common_elements))

def method4():
common_elements = set(li1_temp).intersection(li2_temp)
print(len(common_elements))

if __name__ == "__main__":
li1 = []
li2 = []
for i in range(100000):
li1.append(random.randint(0, 10000))
li2.append(random.randint(0, 10000))

li1_temp = list(set(li1))
li2_temp = list(set(li2))

methods = [method1, method2, method3, method4]
for m in methods:
start = time.perf_counter()
m()
end = time.perf_counter()
print(Decimal((end - start)))

If you run this code you can see that if you use list or generator(if you iterate over generator, not just use it. I did this when I forced generator to print length of it), you get nearly same performance. But if you use set you get much better performance. Also if you use intersection method you will get a little bit better performance. the result of each method in my computer is listed bellow:

1. method1: 0.8150673999999999974619413478649221360683441

2. method2: 0.8329545000000001531148541289439890533685684

3. method3: 0.0016547000000000089414697868051007390022277

4. method4: 0.0010262999999999244948867271887138485908508

this is my premise i think its simplier with sets 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))

## Related questions

1 vote
25 views
Problem: Hello kodlogs, I know the core python but when I have to implement the list concept with this that applying with two lists don't know how to implement this having issue, basically, I come from the c background and in c language there was not any concept of this ... I can see the content of the list is same still I am getting the error dont know how to achieve this waiting for the reply.
1 vote
32 views
Problem: I was trying to find common elements in two lists python. So I wrote this code: x = [1, 2, 6, 9] y = [1, 3, 8, 9] x_as_set = set(y) intersection =x_as_set.intersection(y) intersection_as_list = list(intersection) print(intersection_as_list) But when I compile this it gives error. Please help me to find common elements in two lists python
19 views
Problem: but I'm having a hard time finding the answer. When I compare 2 lists, I want to know if they are "equal" in that they have the same contents, but in different order. Ex: x = ['a', 'b'] y = ['b', 'a'] I want x == y to evaluate to True.
44 views
Problem: I have two ArrayList objects with three integers each. I want to find a way to return the common elements of the two lists Use Collection#retainAll(). listA.retainAll(listB); // listA now contains only the elements which are also contained in listB.
4 views
Problem: Can someone guide me with the project query I am stuck on How to compare two lists in python?
25 views
Problem: Hello kodlogs, I know the core python but when I have to implement the list concept with this that applying with two lists don't know how to implement this having issue.waiting for the reply and what is the possible way to achieve this. import itertools num = [1, 2, 3] color = ['red', 'while', 'black'] for (a, b) in (num, color): print (a, b) Getting error dont know to fix this.