2.3.4. Interaction Between 2 Lists# 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']

{'matplotlib', 'numpy', 'pandas', 'statsmodel'} 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))
['statsmodel', 'numpy'] 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))
# Find elements in requirement2 but not in requirement1
diff = set(requirement2).difference(set(requirement1))