Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

a set must be unique. So, even though the student Raz Pi was in both sets, he is listed only one time in
the union set, students_union.


Set Intersection


A set intersection contains set members that are also members in both a first and a second set. For
example, in Listing 9.20, the student Raz Pi is in both sets students_in_108 and
students_in_133. Therefore, an intersection of those two sets produces a set containing that
student, Raz Pi (see Listing 9.21).


LISTING 9.21 Performing a Set Intersection


Click here to view code image


>>> students_inter = students_in_108.intersection(students_in_133)
>>> students_in_108
{'Paul Bohall', 'Raz Pi', 'Jason Jones'}
>>> students_in_133
{'Raz Pi', 'Benny Lora', 'Jody Sanchez'}
>>> students_inter
{'Raz Pi'}
>>>

Set Difference


A set difference, also called a set complement, is a created third set that contains items in the first set
that are not in the second set. In essence, you subtract the second set from the first set, and the set
difference is whatever is left.


Listing 9.22 shows an example of set difference. Using again the set of students in the 108 and 133
classes, the students_in_108 set has subtracted from it the students_in_133 set. This
removes only the Raz Pi student. Thus, the resulting difference set contains Jason Jones and Paul
Bohall.


LISTING 9.22 Performing a Set Difference


Click here to view code image


>>> students_dif = students_in_108.difference(students_in_133)
>>> students_in_108
{'Paul Bohall', 'Raz Pi', 'Jason Jones'}
>>> students_in_133
{'Raz Pi', 'Benny Lora', 'Jody Sanchez'}
>>> students_dif
{'Paul Bohall', 'Jason Jones'}
>>>

Notice in Listing 9.22 that even though there are students in the students_in_133 set that are not
in the students_in_108 set, subtracting them has no ill effects. Using the difference operator,
you can subtract set elements that do not exist in the original set without throwing an error exception.


Symmetric Set Difference

Free download pdf