2.3.4. Interaction Between 2 Lists#

2.3.4.1. set.union: Find the Union of Two Sets#

To obtain all unique elements from two lists, convert the lists to sets and then use the set.union method to find the union of the two sets.

requirement1 = ['pandas', 'numpy', 'statsmodel']
requirement2 = ['numpy', 'statsmodel', 'matplotlib']

set(requirement1).union(set(requirement2))
{'matplotlib', 'numpy', 'pandas', 'statsmodel'}

2.3.4.2. set.intersection: Find the Intersection Between Two Sets#

To get the common elements between two lists, convert the lists to sets then use the set.intersection method to find the intersection between two sets.

intersection = set(requirement1).intersection(set(requirement2))
list(intersection)
['statsmodel', 'numpy']

2.3.4.3. Set Difference: Find the Difference Between Two Sets#

To find the difference between 2 lists, turn those lists into sets then apply the difference() method to the sets.

# Find elements in requirement1 but not in requirement2
diff = set(requirement1).difference(set(requirement2))
print(list(diff)) 
['pandas']
# Find elements in requirement2 but not in requirement1
diff = set(requirement2).difference(set(requirement1))
print(list(diff)) 
['matplotlib']