Python3 Sets
A set is an unordered collection of unique elements.
Sets can be created using curly braces { } or the set() function. Note: To create an empty set, you must use set(), not { }, because { } is used to create an empty dictionary.
Creation format:
parame = {value01, value02, ...}
or
set(value)
Example (Python 3.0+)
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # Demonstrates the deduplication feature
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # Quickly checks if an element is in the set
True
>>> 'crabgrass' in basket
False
>>> # Demonstrates operations between two sets.
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # Elements in set a but not in set b
{'r', 'd', 'b'}
>>> a | b # Elements in either set a or set b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # Elements in both set a and set b
{'a', 'c'}
>>> a ^ b # Elements not in both set a and set b
{'r', 'd', 'b', 'm', 'z', 'l'}
Similar to list comprehensions, sets also support set comprehensions:
Example (Python 3.0+)
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
Basic Set Operations
1. Add Elements
Syntax format:
s.add(x)
Adds element x to set s. If the element already exists, no action is taken.
Example (Python 3.0+)
>>> thisset = set(("Google", "tutorialpro", "Taobao"))
>>> thisset.add("Facebook")
>>> print(thisset)
{'Taobao', 'Facebook', 'Google', 'tutorialpro'}
There is another method to add elements, which can take a list, tuple, dictionary, etc. The syntax format is as follows:
s.update(x)
x can be multiple elements, separated by commas.
Example (Python 3.0+)
>>> thisset = set(("Google", "tutorialpro", "Taobao"))
>>> thisset.update({1, 3})
>>> print(thisset)
{1, 3, 'Google', 'Taobao', 'tutorialpro'}
>>> thisset.update([1, 4], [5, 6])
>>> print(thisset)
{1, 3, 4, 5, 6, 'Google', 'Taobao', 'tutorialpro'}
>>>
2. Remove Elements
Syntax format:
s.remove(x)
Removes element x from set s. If the element does not exist, an error occurs.
Example (Python 3.0+)
>>> thisset = set(("Google", "tutorialpro", "Taobao"))
>>> thisset.remove("Taobao")
>>> print(thisset)
{'Google', 'tutorialpro'}
>>> thisset.remove("Facebook") # Error occurs if the element does not exist
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Facebook'
>>>
There is another method to remove elements from a set without causing an error if the element does not exist. The format is as follows:
s.discard(x)
Example (Python 3.0+)
>>> thisset = set(("Google", "tutorialpro", "Taobao"))
>>> thisset.discard("Facebook") # No error if not present
>>> print(thisset)
{'Taobao', 'Google', 'tutorialpro'}
We can also randomly remove an element from the set with the following syntax:
s.pop()
Script Mode Example (Python 3.0+)
thisset = set(("Google", "tutorialpro", "Taobao", "Facebook"))
x = thisset.pop()
print(x)
Output:
$ python3 test.py
tutorialpro
The results may vary each time the test is run.
The pop method of a set will randomly order the elements and then remove the first element of this ordered set.
3. Count the Number of Elements in a Set
Syntax:
len(s)
Returns the number of elements in set s.
Example (Python 3.0+)
>>> thisset = set(("Google", "tutorialpro", "Taobao"))
>>> len(thisset)
3
4. Clear a Set
Syntax:
s.clear()
Clears all elements from set s.
Example (Python 3.0+)
>>> thisset = set(("Google", "tutorialpro", "Taobao"))
>>> thisset.clear()
>>> print(thisset)
set()
5. Check if an Element Exists in a Set
Syntax:
x in s
Checks if element x is in set s, returns True if present, otherwise False.
Example (Python 3.0+)
>>> thisset = set(("Google", "tutorialpro", "Taobao"))
>>> "tutorialpro" in thisset
True
>>> "Facebook" in thisset
False
>>>
Complete List of Set Methods
| Method | Description |
|---|---|
| add() | Adds an element to the set |
| clear() | Removes all elements from the set |
| copy() | Returns a copy of the set |
| difference() | Returns the difference of two or more sets as a new set |
| difference_update() | Removes all elements of another set from this set |
| discard() | Removes a specified element from the set if it is present |
| intersection() | Returns the intersection of two sets as a new set |
| intersection_update() | Updates the set with the intersection of itself and another |
| isdisjoint() | Returns True if two sets have a null intersection |
| issubset() | Returns True if another set contains this set |
| issuperset() | Returns True if this set contains another set |
| pop() | Removes and returns an arbitrary set element |
| remove() | Removes a specified element from the set |
| symmetric_difference() | Returns the symmetric difference of two sets as a new set |
| symmetric_difference_update() | Updates the set with the symmetric difference of itself and another |
| union() | Returns the union of sets in a new set |
| update() | Updates the set with the union of itself and others |
| symmetric_difference_update() | Removes elements that are in both the current set and another specified set, and inserts elements from the other set that are not in the current set. |
| union() | Returns the union of two sets. |
| update() | Adds elements to the set. |