Find the common items from two lists using set(). intersection() Example 3- Using set( ). intersection(), We can print the list of common elements of a list, but it can not store in any of the variables.
For the two lists to be equal, each element of the first list should be equal to the second list's corresponding element. If the two lists have the same elements, but the sequence is not the same, they will not be considered equal or identical lists.
Use the intersection function to check if both sets have any elements in common. If they have many elements in common, then print the intersection of both sets.
Use Python's set intersection:
>>> 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.
You can solve this using numpy
:
import numpy as np
list1 = [1, 2, 3, 4, 5, 6]
list2 = [3, 5, 7, 9]
common_elements = np.intersect1d(list1, list2)
print(common_elements)
common_elements
will be the numpy array: [3 5]
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With