Skip to content

Python3 Sets

A set is an unordered sequence of non-repeating elements.

Elements in a set do not repeat, and common set operations such as intersection, union, and difference can be performed.

Sets can be created using curly braces { } with elements separated by commas, or using the set() function.

Creation format:

parame = {value01,value02,...}
or
set(value)

Here is a simple example:

set1 = {1, 2, 3, 4}            # Create a set directly using curly braces
set2 = set([4, 5, 6, 7])      # Create a set from a list using the set() function

Note: To create an empty set, you must use set() instead of { }, because { } is used to create an empty dictionary.

More example demonstrations:

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # This demonstrates deduplication
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # Quickly check if an element is in the set
True
>>> 'crabgrass' in basket
False

>>> # Below shows 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                              # All elements in set a or b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # Elements in both set a and b
{'a', 'c'}
>>> a ^ b                              # Elements not in both a and b simultaneously
{'r', 'd', 'b', 'm', 'z', 'l'}

Similar to list comprehensions, sets also support set comprehensions:

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

Syntax format:

s.add( x )

Adds element x to set s. If the element already exists, no operation is performed.

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.add("Facebook")
>>> print(thisset)
{'Taobao', 'Facebook', 'Google', 'Runoob'}

There is another method that can also add elements, and its parameters can be lists, tuples, dictionaries, etc. The syntax format is as follows:

s.update( x )

x can have multiple values, separated by commas.

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.update({1,3})
>>> print(thisset)
{1, 3, 'Google', 'Taobao', 'Runoob'}
>>> thisset.update([1,4],[5,6])  
>>> print(thisset)
{1, 3, 4, 5, 6, 'Google', 'Taobao', 'Runoob'}
>>> 

Syntax format:

s.remove( x )

Removes element x from set s. If the element does not exist, an error will occur.

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.remove("Taobao")
>>> print(thisset)
{'Google', 'Runoob'}
>>> thisset.remove("Facebook")   # An error will occur if the element does not exist
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Facebook'
>>> 

There is also another method for removing elements from a set, and it will not raise an error if the element does not exist. The format is as follows:

s.discard( x )
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.discard("Facebook")  # No error if the element does not exist
>>> print(thisset)
{'Taobao', 'Google', 'Runoob'}

We can also randomly remove an element from the set. The syntax format is as follows:

s.pop() 
thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
x = thisset.pop()

print(x)

Output:

Runoob

The result varies each time it is executed.

The pop method of a set will arrange the set in an unordered manner and then remove the first element from the left of this unordered arrangement.

Syntax format:

len(s)

Counts the number of elements in set s.

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> len(thisset)
3

Syntax format:

s.clear()

Clears set s.

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.clear()
>>> print(thisset)
set()

Syntax format:

x in s

Checks if element x is in set s. Returns True if it exists, otherwise returns False.

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> "Runoob" in thisset
True
>>> "Facebook" in thisset
False
>>> 
Method Description
add() Adds an element to the set
clear() Removes all elements from the set
copy() Copies a set
difference() Returns the difference of multiple sets
difference_update() Removes elements from the set that also exist in the specified set.
discard() Deletes a specified element from the set
intersection() Returns the intersection of sets
intersection_update() Returns the intersection of sets.
isdisjoint() Determines whether two sets contain the same elements. Returns True if they do not, otherwise False.
issubset() Determines whether the specified set is a subset of the method’s argument set.
issuperset() Determines whether the method’s argument set is a subset of the specified set
pop() Randomly removes an element
remove() Removes the specified element
symmetric_difference() Returns the set of non-repeating elements from two sets.
symmetric_difference_update() Removes elements in the current set that are the same as elements in another specified set, and inserts elements from the other specified set that are different into the current set.
union() Returns the union of two sets
update() Adds elements to the set
len() Counts the number of elements in the set