Overview of Sets in Python
To be successful you should follow these tasks weekly
read the overview page in each assigned module
read the lecture notes posted in modules
participate in the discussion forums
review the supplement documents and example code posted in the modules
attempt the practice exercise in the module
complete the module assignments
complete the module quiz
Important Reminder
The correct process for responding to discussions is to first post your own reply to the discussion topic. Other participant’s replies will not be visible until you post your first individual reply. Second, you must post a brief reply to at least two other students’ replies. This along with a relevant individual reply will give you full credit in discussion assignments.
Sets
A set contains a collection of unique values and works like a mathematical set. A set is an object that stores a collection of data in the same way as mathematical sets.
Here are some important things to know about sets:
- All the elements in a set must be unique. No two elements can have the same value.
- Sets are unordered, which means that the elements in a set are not stored in any particular order.
- The elements that are stored in a set can be of different data types.
Creating a Set
To create a set, you have to call the built-in set function.
Here is an example of how you create an empty set:
myset = set()
After this statement executes, the myset variable will reference an empty set. You can also pass one argument to the set function. The argument that you pass must be an object that contains iterable elements, such as a list, a tuple, or a string. The individual elements of the object that you pass as an argument become elements of the set.
Here is an example:
myset = set(['a', 'b', 'c'])
In this example we are passing a list as an argument to the set function. After this statement executes, the myset variable references a set containing the elements 'a', 'b', and 'c'. If you pass a string as an argument to the set function, each individual character in the string becomes a member of the set
Here is an example:
myset = set('abc')
After this statement executes, the myset variable will reference a set containing the elements
'a', 'b', and 'c'.
Sets cannot contain duplicate elements. If you pass an argument containing duplicate elements to the set function, only one of the duplicated elements will appear in the set.
Here is an example:
myset = set('aaabc')
The character 'a' appears multiple times in the string, but it will appear only once in the set. After this statement executes, the myset variable will reference a set containing the elements
'a', 'b', and 'c'.
Here is an example:
# OK, this works.
myset = set(['one', 'two', 'three'])
After this statement executes, the myset variable will reference a set containing the elements 'one', 'two', and 'three'.
Getting the Number of Elements in a Set
As with lists, tuples, and dictionaries, you can use the len function to get the number of elements in a set. The following interactive session demonstrates:
myset = set([1, 2, 3, 4, 5])
len(myset)
Adding and Removing Elements
Sets are mutable objects, so you can add items to them and remove items from them. You use the add method to add an element to a set.
The following interactive session demonstrates:
myset = set()
myset.add(1)
myset.add(2)
myset.add(3)
You can add a group of elements to a set all at one time with the update method. When you call the update method as an argument, you pass an object that contains iterable elements, such as a list, a tuple, string, or another set. The individual elements of the object that you pass as an argument become elements of the set.
The following interactive session demonstrates:
myset = set([1, 2, 3])
myset.update([4, 5, 6])
myset
This diplays the following result: {1, 2, 3, 4, 5, 6}
You can remove an item from a set with either the remove method or the discard method. You pass the item that you want to remove as an argument to either method, and that item is removed from the set. The only difference between the two methods is how they behave when the specified item is not found in the set. The remove method raises a KeyError exception, but the discard method does not raise an exception.
The following statements demonstrates this:
myset = set([1, 2, 3, 4, 5])
myset
myset.remove(1)
myset
This procuces this result: {2, 3, 4, 5}
myset.discard(5)
myset
This produces this result: {2, 3, 4}
Use a for Loop to Iterate over a Set
You can use the for loop in the following general format to iterate over all the elements
in a set:
for var in set:
statement
statement
In the general format, var is the name of a variable and set is the name of a set. This loop iterates once for each element in the set. Each time the loop iterates, var is assigned an element.
Finding the Union of Sets
The union of two sets is a set that contains all the elements of both sets. In Python, you can call the union method to get the union of two sets.
Here is the general format:
set1.union(set2)
In the general format, set1 and set2 are sets. The method returns a set that contains the elements of both set1 and set2.
The following interactive session demonstrates:
set1 = set([1, 2, 3, 4])
set2 = set([3, 4, 5, 6])
set3 = set1.union(set2)
set3
displays this Result Set: {1, 2, 3, 4, 5, 6}
Finding the Intersection of Sets
The intersection of two sets is a set that contains only the elements that are found in both sets. In Python, you can call the intersection method to get the intersection of two sets.
Here is the general format:
set1.intersection(set2)
In the general format, set1 and set2 are sets. The method returns a set that contains the elements that are found in both set1 and set2.
The following interactive demonstrates this:
set1 = set([1, 2, 3, 4])
set2 = set([3, 4, 5, 6])
set3 = set1.intersection(set2)
set3
This is the result set of an intersection of set1 and set2: {3, 4}
You can also use the & operator to find the intersection of two sets.
Here is the general format of an expression using the & operator with two sets:
set1 & set2
In the general format, set1 and set2 are sets. The expression returns a set that contains
the elements that are found in both set1 and set2. The following interactive session demonstrates:
set1 = set([1, 2, 3, 4])
set2 = set([3, 4, 5, 6])
set3 = set1 & set2
set3
Once again it returns the following result set: {3, 4}
The following code demonstrates this:
set1 = set([1, 2, 3, 4])
set2 = set([3, 4, 5, 6])
set3 = set1.difference(set2)
set3
This produces this result set: {1, 2}
You can also use the - operator to find the difference of two sets. Here is the general format
of an expression using the - operator with two sets:
set1 − set2
In the general format, set1 and set2 are sets. The expression returns a set that contains
the elements that are found in set1 but not in set2. The following interactive session demonstrates:
set1 = set([1, 2, 3, 4])
set2 = set([3, 4, 5, 6])
set3 = set1 − set2
set3
This produces this result set: {1, 2}
Homework
Readings
Discussions for the Week
None
Weekly Quiz