# Common elements comparison between 2 lists

Posted on

### Question :

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?

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

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:

``````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.

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.

``````list1 = [1,2,3,4,5,6]
list2 = [3,5,7,9]
``````

I know 3 ways can solve this, Of course, there could be more.

1-

``````common_elements = [e for e in list1 if e in list2]
``````

2-

``````import numpy as np
common_elements = np.intersect1d(list1, list2)
``````

3-

``````common_elements = set(list1).intersection(list2)
``````

The 3rd way is the fastest because Sets are implemented using hash tables.

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]
``````

Set is another way we can solve this

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

``````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`.