A set represent an unordered collection of unique elements. This data type represents the Mathematical notion of set. 

Sets in Python are mutable, however,  they can only contain immutable elements such as strings, tuples, integers, etc.  A  set cannot contain a mutable element such as a list , a dictionary or even another set. 

In Python elements in a set are enclosed in curly braces, {}.  However, to initialize an empty set, we can only use the builtin set() function. as shown below:

set()

We cannot use empty curly braces , this is because, the curly braces are also used in Python dictionaries. Python will interpret empty curly braces as an empty dictionary instead of an empty set.

ExampleEdit & Run
x = {}
print(type(x))
copy
Output:
<class 'dict'> [Finished in 0.010426886845380068s]

But for a non-empty set there is no ambiguity because the syntax for set elements  and dictionaries are different. It is therefore fine to use the curly braces to initialize a non-empty set:

ExampleEdit & Run
S = {1, 2, 3, 4, 5}
print(type(S))

S1 = {'Python', 'Javascript', 'CSS'}
S2 = {1.0, 2.0, 3.0}
copy
Output:
<class 'set'> [Finished in 0.010206265840679407s]

Elements in a set are unique, this means that an item will only be included once even if it appears more than once during initialization. 

ExampleEdit & Run
S = {'Python', 'Python', 'Python', 'Python'}
print(S)

S1 = {'Python', 'C++', 'Javascript', 'Java', 'CSS', 'Html', 'CSS', 'Java', 'C++'}
print(S1)
copy
Output:
{'Python'} {'Javascript', 'CSS', 'Html', 'Java', 'C++', 'Python'} [Finished in 0.010025700088590384s]

The set() function is also used to cast other supported  sequential types such as lists, tuples, etc. to sets. Examples:

ExampleEdit & Run
s1 = set( [1, 2, 3] )  #list to set
print(s1)

s2 = set( ('Python', 'CSS', 'PHP') )  #tuple to set
print(s2)
copy
Output:
{1, 2, 3} {'PHP', 'CSS', 'Python'} [Finished in 0.009712014347314835s]

As we said the elements in a set are also unordered. While Python will sometimes show the elements in their order of initialization, this is not a guaranteed order like in other data types such as lists and tuples. This also means that we cannot access elements in a set through indexing or slicing.

Sets in Python use a hashtable implementation to efficiently store and retrieve elements based on their hash value. Since lists , dictionaries and sets are mutable and their hash values can change, they are not allowed as elements in a set. Trying to store unhashable elements in a set will raise a TypeError.

ExampleEdit & Run
S = {[2, 3], [2, 3]}
copy
Output:
Traceback (most recent call last):   File "<string>", line 1, in <module> TypeError: unhashable type: 'list' [Finished in 0.010370596777647734s]

Set Operations and Methods

Most operations common to other sequential data types such as concatenation , repetition , indexing and slicing are not applicable to sets. This mostly stems from the fact that items in sets are unordered and unique, most of this operations such as concatenation and indexing implies a specific order while others such as repetition would violate the uniqueness property of sets. Instead, sets have some other unique set of operations , which we will discuss here.

Set Union

The union of two sets is the set of all the elements of both the sets without duplicates. You can use the union() method or the | syntax to find the union of a Python set.

ExampleEdit & Run
S1 = {1, 2, 3, 4, 5}
S2 = {3, 4, 5, 6, 7}

print( S1.union(S2) )
print( S1 | S2 )
copy
Output:
{1, 2, 3, 4, 5, 6, 7} {1, 2, 3, 4, 5, 6, 7} [Finished in 0.009552319999784231s]

Set Intersection

The intersection of two sets is the set of all the common elements of both sets. You can use the intersection() method or the & operator to find the intersection of a Python set.

ExampleEdit & Run
S1 = {0, 1, 2, 3, 4, 5}
S2 = {6, 7, 8, 9}
S3 = {0, 2, 4, 6, 8}

print( S1.intersection(S2) ) #no common elements, therefore, returns an empty set.
print(S1 & S3) #{0, 2, 4}
print(S2 & S3)
copy
Output:
set() {0, 2, 4} {8, 6} [Finished in 0.009431274142116308s]

Set Difference

The difference between two sets is the set of all the elements in first set that are not present in the second set. You can use the difference() method or the - operator to achieve this in Python.

ExampleEdit & Run
S1 = {0, 1, 2, 3, 4, 5}
S2 = {6, 7, 8, 9}
S3 = {0, 2, 4, 6, 8}

print(S1.difference(S2))
print(S2.difference(S1))
print(S1 - S3)
print(S2 - S3)
copy
Output:
{0, 1, 2, 3, 4, 5} {8, 9, 6, 7} {1, 3, 5} {9, 7} [Finished in 0.009811053983867168s]

Set Symmetric Difference

The symmetric difference between two sets is the set of all the elements that are either in the first set or the second set but not in both. We can use the symmetric_difference or the operator.

ExampleEdit & Run
S1 = {0, 1, 2, 3, 4, 5}
S2 = {6, 7, 8, 9}
S3 = {0, 2, 4, 6, 8}

print( S1.symmetric_difference(S2) )
print( S1 ^ S3 ) 
print( S2 ^ S3 )
copy
Output:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} {1, 3, 5, 6, 8} {0, 2, 4, 7, 9} [Finished in 0.009236529003828764s]

Other set Methods

issubset()

Syntax:
S1.issubset(S2)
copy

This methods returns True if all the elements of set S1 are in S2 , else False.

ExampleEdit & Run
S1 = {1, 3, 5, 7, 9}
S2 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
S3 = {0, 2, 4, 6, 8}

print( S1.issubset(S2) ) 
print( S3.issubset(S2) )
print( S2.issubset(S1) )
print( S3.issubset(S1) )
copy
Output:
True True False False [Finished in 0.009543119929730892s]

issuperset():

Syntax:
S1.issuperset(S2)

This method returns True if all the elements in S2 are in S1, else False.

ExampleEdit & Run
S1 = {1, 3, 5, 7, 9}
S2 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
S3 = {0, 2, 4, 6, 8}

print( S2.issuperset(S1) )
print( S2.issubset(S3) )
print( S1.issuperset(S2) )
print( S3.issuperset(S1) )
copy
Output:
True False False False [Finished in 0.010289852973073721s]

isdisjoint()

This method returns True if there are no common elements between S1 and S2, else False.

ExampleEdit & Run
S1 = {1, 3, 5, 7, 9}
S2 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
S3 = {0, 2, 4, 6, 8}

print( S1.isdisjoint(S2) )
print( S1.isdisjoint(S3) )
copy
Output:
False True [Finished in 0.009724313393235207s]

add()

Syntax:
S.add(x)
copy

This method is used to add an element, x to the Set S, if the element already exist in the set, it is ignored in order to maintain the uniqueness property.

ExampleEdit & Run
S = {1, 3, 5}
S.add(7)
print(S)

S.add(9)
print(S)

S.add(5)
print(S)
copy
Output:
{1, 3, 5, 7} {1, 3, 5, 7, 9} {1, 3, 5, 7, 9} [Finished in 0.009648019913583994s]

update()

Syntax:
S.update(seq)
copy

This method is used to add all the elements of the sequence, seq to the set S.

ExampleEdit & Run
S = {1, 3, 5}
S.update([7, 9, 11])
print(S)
copy
Output:
{1, 3, 5, 7, 9, 11} [Finished in 0.009728089906275272s]

remove()

Syntax:
S.remove(x)
copy

This method removes element x from set S, a KeyError is raised if element x is not found in the set.

ExampleEdit & Run
S = {1, 3, 4, 5, 7, 9}
S.remove(4)
print(S)

S.remove(10) #keyError
copy
Output:
{1, 3, 5, 7, 9} Traceback (most recent call last):   File "<string>", line 5, in <module> KeyError: 10 [Finished in 0.009437252301722765s]

discard()

Syntax:
S.discard(x)
copy

Removes element x from set S, but unlike remove(), no KeyError is raised if the element is not found.

ExampleEdit & Run
S = {1, 3, 4, 5, 7, 9}
S.discard(4)
print(S)

S.discard(10)
print(S)
copy
Output:
{1, 3, 5, 7, 9} {1, 3, 5, 7, 9} [Finished in 0.009712900966405869s]

pop()

Syntax:
S.pop() 
copy

This method removes and returns a random element in the set S, a KeyError is raised if the set is empty.

ExampleEdit & Run
S = {0, 2, 4}

print( S.pop() )
print( S.pop() )
print( S.pop() )

print( S.pop() ) #keyError
copy
Output:
0 2 4 Traceback (most recent call last):   File "<string>", line 7, in <module> KeyError: 'pop from an empty set' [Finished in 0.00987780001014471s]

clear()

Syntax:
S.clear()
copy

Removes all elements from set S effectively making it an empty set.

ExampleEdit & Run
S = {1, 2, 3, 4, 5}
S.clear()
print(S)
copy
Output:
set() [Finished in 0.009700344875454903s]