Sets
A set contains a collection of unique values and works like a mathematical set. 1) all items in a set must be unique (no same values); 2) sets are unordered; 3) the elements that are stored in a set can be of different data types.
Syntax and Methods
We use the built-in function set to create a set:
myset = set()
You can get the number of elements in the set by using the len function.
You can add and remove elements in the set. You use the add Method to add an element to a set. You use the remove Method or the discard Method to remove an item from the set.
You can use the for Loop to iterate over a set.
for var in set:
statement
statement
etc.
You can use the in and not in Operators to Test for a Value in a set.
You can use the union Method to get the union of two sets.
set1.union(set2)
You can use the intersection Method to get the intersection of two sets.
set1.intersection(set2)
You can use the difference Method to get the difference of two sets. (elements that appear in set 1 but do not appear in set 2.
set1.difference(set2)
You can use the symmetric_difference Method to get the symmetric difference of two sets (elements that are not shared by the sets).
set1.symmetric_difference(set2)
Serializing Objects
Serializing an object is the process of converting the object to a stream of bytes that can be saved to a file for later retrieval. This is called "pickling". The PYTHON library provides a module named pickle that holds various functions that serialize objects.
Exercises
Note the >>> prompt in the examples below indicates that they are running in the PYTHON shell using the "interactive" mode.
>>> nums = {3, 2, 5, 7, 1, 6.3}
>>> nums
{1, 2, 3, 5, 6.3, 7}
>>> primes = {3, 2, 11, 3, 5, 13, 2}
>>> primes
{2, 3, 5, 11, 13}
>>> nums.union(primes)
{1, 2, 3, 5, 6.3, 7, 11, 13}
>>> primes.difference(nums)
{11, 13}
>>> nums.difference(primes)
{1, 6.3, 7}
>>> len(nums)
6
>>> nums[0]
Traceback (most recent call last):
File "
TypeError: 'set' object does not support indexing
>>> book
'Alchemist'
>>> set(book)
{'i', 'l', 's', 'A', 'e', 'h', 'm', 't', 'c'}
>>> set([1, 5, 3, 1, 9])
{1, 3, 5, 9}
>>> list(set([1, 5, 3, 1, 9]))
[1, 3, 5, 9]
>>> nums = {1, 2, 3, 5, 6.3, 7}
>>> nums
{1, 2, 3, 5, 6.3, 7}
>>> nums.pop()
1
>>> nums
{2, 3, 5, 6.3, 7}
>>> nums.add(1)
>>> nums
{1, 2, 3, 5, 6.3, 7}
>>> 6.3 in nums
True
>>> for n in nums:
print(n)
1
2
3
5
6.3
7