Skip to main content

Discrete Math with SageMath: Learn math with open-source software

Section 2.1 Creating Sets

Subsection 2.1.1 Set Definitions

To construct a set, encase the elements within square brackets []. Then, pass this list as an argument to the Set() function. It’s important to note that the S in Set() should be uppercase to define a Sage set. In a set, each element is unique.
Notice that the months in set \(M\) do not appear in the same order as when you created the set. Sets are unordered collections of elements.
We can ask Sage to compare two sets to see whether or not they are equal. We can use the == operator to compare two values. A single equal sign = and double equal sign == have different meanings.
The equality operator == is used to ask Sage if two values are equal. Sage compares the values on each side of the operator and returns the Boolean value. The == operator returns True if the sets are equal and False if they are not equal.
The assignment operator = assigns the value on the right side to the variable on the left side.
If you have experience with Python, you may have used a Python set. Notice how the Python set begins with a lowercase s. Even though Sage supports Python sets, we will use Sage Set for the added features. Be sure to define Set() with an upper case S.

Subsection 2.1.2 Set Builder Notation

Instead of explicitly listing the elements of a set, we can use a set builder notation to define a set. The set builder notation is a way to define a set by describing the properties of its elements. Here, we use the Sage srange instead of the Python range function for increased flexibility and functionality.
Iteration is a way to repeat a block of code multiple times and can be used to automate repetitive tasks. We could have created the same set by typing A = Set([2, 4, 6, 8, 10]). Imagine if we wanted to create a set of even numbers between 1 and 100. It would be much easier to use iteration.

Subsection 2.1.3 Subsets

To list all the subsets included in a set, we can use the Subsets() function and then use a for loop to display each subset.

Subsection 2.1.4 Set Membership Check

Sage allows you to check whether an element belongs to a set. You can use the in operator to check membership, which returns True if the element is in the set and False otherwise.
We can check if \(Severe = \{Tornado, Hurricane \}\) is a subset of \(W\) by using the issubset method.
When we evaluate W.issubset(Severe), Sage returns False because \(W\) is not a subset of \(Severe\text{.}\)