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

(singke) #1

A symmetric set difference is a created third set that contains only elements that are solely in one set
or the other. Thus, looking at the student example, a symmetric set difference would contain all the set
elements from both students_in_108 and students_in_133, except for Raz Pi. Since Raz
Pi is in both sets, he would be excluded from the symmetric set difference, as shown in Listing 9.23.


LISTING 9.23 Performing a Symmetric Set Difference


Click here to view code image


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

Traversing a Set


Using a loop to obtain elements from a set is very easy because the set itself can be used for iteration.
Listing 9.24 shows an example of this.


LISTING 9.24 Showing a Set Traversed


Click here to view code image


>>> for the_student in students_in_133:
... print (the_student)
...
Raz Pi
Benny Lora
Jody Sanchez
>>>

Notice that the for loop has no problems traversing the set. However, due to the unordered nature of
sets, you can potentially end up with an unordered display.


By the Way: A Sort Would Change the Type
You could use the sorted function to sort a set. However, be aware that sorted
will convert the set to a list object type!

Modifying a Set


A set is not immutable, and thus it can be changed. Updating a set does not mean changing individual
elements within a set. For example, going back to the student set example, in students_in_108,
the element 'Paul Bohall' cannot be updated to be 'Sam Bohall' because sets have no
indexing capabilities. Updating a set actually means conducting a mass addition to the set.


To perform an update on a set, you use this syntax:

Free download pdf