Creating Sets and Performing Set Operations:

  • Unlike dictionaries that hold data in a way that allows values to be associated with keys, sets hold groups of unique elements in no particular order but in a way that makes certain kinds of calculations very easy and fast.

  • In the same way that we can use some operators, such as + - * / β€” to perform calculations on numbers, we can also use operators in Python to perform calculations on sets, such as:

    • set1 & set2: return the intersection between set1 and set2 β€” the & is an β€œand” operator, answering the question β€œwhat is in set1 and set2?”
    • set1 | set2: return the union between set1 and set2 β€” the | is an β€œor” operator, answering the question β€œwhat is in set1 or set2?”
    • set1 - set2: return the set of elements in set1 that are not in set2 β€” as in subtract the elements of set2 from set1, and return the difference

Unit Wrap-Up Assignment (Not a Deliverable):

  • Examine the figure representing a Venn Diagram for two sets of marbles and the two different Python sets: my_marbles and your_marbles.

Venn diagram with three labeled regions A, B, and C showing my_marbles and your_marbles sets with shared elements

python
1my_marbles = {'black', 'green', 'blue', 'red', 'purple', 'yellow', 'cyan'}
2your_marbles = {'green', 'magenta', 'red', 'brown', 'black', 'gray'}
  • In a new Python file, do the following:
    • Write a Python expression that computes the elements that are in Region A of the Venn Diagram, and assign the result to the variable regionA.
    • Write a Python expression that computes the elements that are in Region B of the Venn Diagram, and assign the result to the variable regionB.
    • Write a Python expression that computes the elements that are in Region C of the Venn Diagram, and assign the result to the variable regionC.
    • Write a Python expression that computes the elements that are in any Region of the Venn Diagram, and assign the result to the variable regionABC.