In order to create the elements properly, they must be between brackets. In this example, the elements
are all strings, but the elements can also be integers, floating-point numbers, lists, tuples, and so on.
Obtaining Information from a Set
The primary value of sets is what mathematics calls set theory. You can easily determine what
particular element is in multiple sets, how sets are different from one another, whether one element is
unique in a group of sets, and so on.
Set Membership
You can determine whether an element belongs to a particular set. As shown in Listing 9.19, you can
use an if statement to check a set for an element’s membership.
LISTING 9.19 Checking a Set for Element Membership
Click here to view code image
>>> student = 'Raz Pi'
>>> if student in students_in_108:
... print (student, "is in 'Python Set Fundamentals' class.")
... else:
... print (student, "is not in the class.")
...
Raz Pi is in 'Python Set Fundamentals' class.
>>>
As you can see in Listing 9.19, the student Raz Pi does have membership in the
students_in_108 set.
Set Union
A set union is where all the elements from two sets are combined to create a third set. You do not
create a set union by using the + operand. Rather, you use the following syntax:
set_name#1.union(set_name#2)
Listing 9.20 is an example of combining sets into a union.
LISTING 9.20 Performing a Set Union
Click here to view code image
>>> students_union = students_in_108.union(students_in_133)
>>> students_in_108
{'Paul Bohall', 'Raz Pi', 'Jason Jones'}
>>> students_in_133
{'Raz Pi', 'Benny Lora', 'Jody Sanchez'}
>>> students_union
{'Paul Bohall', 'Raz Pi', 'Jason Jones', 'Benny Lora', 'Jody Sanchez'}
>>>
The .union set operative adds the set members together. However, remember that every element in