Python Sets


In this article, you will learn in depth about Python sets from its creation to its modification including adding/removing elements and different operations on them.

Introduction
How to create a sets in Python?
How to add new items in a Python set?
How to remove items from a Python set?
How to iterate through a set in Python?
How to copy a set in a set in Python?
Python mathematical set operations
What is a Python frozen set?
Python set methods
 python sets

Python Sets: Introduction


A Python set is an unordered collection of comma separated elements inside curly braces '{ }'. Python set itself is mutable allowing addition and removal of items but the elements are immutable which forbids any change in existing items.

Unlike tuples or lists, Python sets don’t allow multiple occurrences of the same element. Hence, each element in Python set is unique.

There are two types of built-in set types:

  • set: Python set type is mutable
  • frozen set: Python frozen set type is immutable

How to create Python sets?


Creating set in Python is as easy as placing unique comma separated items in curly braces '{ }' or it can also be created by using built-in function set( ).

We can’t create empty sets by using only curly braces in Python sets though, we need to use built-in function set( ) to create an empty set.

>>> #creating empty set
>>> py_set = set( )
>>> #creating a set of integers
>>> py_set = {1,2,3,4}

Creating a Python set from a string

We can use built-in function set( ) to create a set from a string. When we pass a string in the function set( ), the string is broken into its singular characters and the characters form a new set. Here is an example.

>>> #creating set from string
>>> py_set = ('Python Sets')
>>> print (py_set)
{'e','y','S','P','s','h','n','o',' ','t'}

As seen on above example, the string is singularized into characters and a set is formed but it contains the random order of the characters.

Creating a Python set from a tuple/list

Creating Python sets from tuples or lists is as simple as putting tuples or lists inside function set( ).

>>> #creating set from a tuple
>>> py_set = set(('a','b','c','d'))
>>> print (py_set)
{'a','b','c','d'}

>>> #creating set from a list
>>> py_set=set(['H','B','O'])
>>> py_set
{'H','B','O'}

Nothing unusual happens when we create Python sets from lists or tuples containing unique elements.

What happens when we try to create Python sets from lists or tuples containing duplicate elements?

Well, we know that Python set is the unordered collection of unique items. So, when we try to create a set from list or tuple containing duplicate items as well, the function set( ) automatically excludes the duplicate items preventing from their multiple occurrences.

Here is the example.

>>> #creating set from a list conataining dplicate items
>>> py_set=set(['H','B','O','O','B'])
>>> py_set
{'H','B','O'}

As seen in above example, while forming set, the duplicate items are excluded automatically.

How to add new items in a Python set?


There are two methods add( ) and update() for adding new items to the Python set.

  • set( ): to add single item
  • update( ): to add multiple items

Duplicate items are automatically avoided while adding new items.

Note: Slicing or indexing operator can’t be used in Python sets to add or access members.

>>> #creating a new set
>>> py_set=set(['a','b','c'])
>>> #Adding a element using add( )
>>> py_set.add('d')
>>> print (py_set)
{'d','a','b','c'}

>>> Adding multiple items using update( )
>>> py_set.update(['e','f'])
>>> print (py_set)
{'e','a','f','b','d','c'}

As seen in above example, the order of the items is random in a set.

How to remove items from a Python set?


While the existing items in a Python set can’t be changed, we can add or remove items. There are certain methods to remove items from a Python set. Each method is illustrated with examples below.

pop( )

Like in lists and tuples, pop( ) is used to remove an item from a Python set. In lists or tuples or dictionary we can remove the desired item specifying in the slicing and indexing operator.

Since slicing and indexing operator is not allowed in sets, an arbitrary item is removed and returned. Here is the example.

>>> py_set = set([1,2,3])
>>> py_set.pop()
1
>>> print (py_set)
{2,3}

remove( )

Using remove( ) function, we can remove any existing item in the Python set by designating and supplying the item as the function argument. It will throw and error if the item doesn’t exist in the set.

>>> py_set = set([1,2,3,4])
>>> py_set.remove(3)
>>> print (py_set)
{1,2,4}

discard( )

discard( ) is another function used to remove an item from the set. It operates same as remove( ) but doesn’t throw an error if the item doesn’t exist in the set.

>>> py_set = set([1,2,3,4])
>>> py_set.discard(2)
>>> print (py_set)
{1,3,4}

clear( )

In Python set, clear( ) is used to remove all the items from the set.

>>> py_set = set([1,2,3])
>>> py_set.clear()
>>> print (py_set)
set()

How to iterate through a set in Python?


We can iterate through each item in a Python set using a for loop.

for letters in set('YOLO'):
   print(letters)

Output

Y
O
L
O

How to copy a set in Python?


To copy a Python set or its items, Python provides built-in function copy( ). It creates a shallow copy and returns it.

>>> py_set1 = set([1,2,3])
>>> #to copy items of py_set1 to py_set
>>> py_set = py_set1.copy()
>>> print (py_set)
{1,2,3}

Python mathematical set operations


Different mathematical operations like union, intersection, and difference can be carried out using Python sets.

Set Union

As the definition goes in the set theory, Set union is defined as the set of collection of all the elements from corresponding sets. It is one of the fundamental operation through which different sets can be related.

In mathematics, union is represented by U.

In Python, union can be achieved by either using | operator or by using built-in function union( ).

>>> set1 = {[1,2,3,4,5]}
>>> set2 = {[3,4,5,6,7]}
>>> #using | operator
>>> set3 = set1 | set2
>>> print (set3)
{[1,2,3,4,5,6,7]}
>>> #using union() function
>>> set3 = set(set1.union(set2))
{1,2,3,4,5,6,7}

Set Intersection

Intersection is the set of common elements in all the sets involved in the operation. It is denoted by  in mathematics.

Intersection can either be performed by using & operator or a built-in function intersection( ).

>>> set1 = {[1,2,3,4,5]}
>>> set2 = {[3,4,5,6,7]}
>>> #using & operator
>>> set3 = set1 & set2
>>> print (set3)
{[3,4,5]}
>>> #using intersection() function
>>> set3 = set(set1.intersection(set2))
{3,4,5}

Set difference

Set difference is the set of unique elements that only exist in the set from which other sets are being subtracted from or differentiated from.

For example, if X and Y are two sets, X - Y will yield a set containing elements that only exist in set X.

This can be achieved by using either - operator or a built-in function difference( ).

>>> set1 = {[1,2,3,4,5]}
>>> set2 = {[3,4,5,6,7]}
>>> #using - operator
>>> set3 = set1 - set2
>>> print (set3)
{[1,2]}
>>> #using difference() function
>>> set3 = set(set1.difference(set2))
{1,2}

Symmetric difference

Symmetric difference is a set of elements containing the unique elements of both the sets involved. The elements which are common to both the sets are excluded.

Symmetric difference is performed either by using ^ operator or by using built-in function symmetric_difference( ).

>>> set1 = {[1,2,3,4,5]}
>>> set2 = {[3,4,5,6,7]}
>>> #using ^ operator
>>> set3 = set1 ^ set2
>>> print (set3)
{[1,2,6,7]}
>>> #using symmetric_difference() function
>>> set3 = set(set1.symmetric_difference(set2))
{1,2,6,7}

As seen in above example, the elements common to both sets 3,4, and 5 are excluded.

Subset and Superset

Any set X is called the subset of Y, if and only if all the elements of X exist in Y. Here X is the subset of Y and Y is the superset of X as Y contains all the elements of X.

In Python, we can check whether or not a set is subset of another by using <= operator or by using built-in function issubset( ). Also we can check superset by using >= operator or using built-in function issuperset( ).

>>> X = {[1,2,3]}
>>> Y = {[1,2,3,4,5,6,7]}
>>> #checking subset using <= operator
>>> X <= Y
TRUE
>>> #using issubset()
>>> X.issubset(Y)
TRUE
>>> #checking superset using >= operator
>>> X >= Y
FALSE 
>>> Y >= X
TRUE
>>> #checking superset using issuperset()
>>> Y.issuperset(X)
TRUE

What is a Python frozen set?


Frozen set is similar to set except in mutability. Python set is mutable itself, however, the elements in the set are immutable. In the frozen set, along with elements frozen set itself is immutable. Hence, We cannot add or remove items from frozen sets.

Frozen sets can be used as keys in the dictionary as they are immutable and hashable.

Frozen sets are created using built-in function frozenset( ).

>>> py_frozenset = frozenset([1,2,3,4,5])

Python Set Methods


Here is the tabulated list if Python set methods used for different kind of operations in sets.

Python set methods with description
set.add( )
Adds an element to the set.
set.clear( )
Remove all the items from the set.
set.copy( )
Returns a shallow copy of the set. Used for copying.
set.difference( )
Returns the difference of two or more sets.
set.discard( )
Removes an element from a set if it exist in the set.
set.intersection( )
Returns the set of common elements between sets i.e intersection.
set.disjoint( )
Returns true if the sets don’t have elements in common i.e null intersection.
set.issubset( )
Returns true if another set contains all the elements of this set.
set.issuperset( )
Returns true if this set contains all the elements of another set.
set.pop( )
Returns and removes an arbitrary item from the set. Raises error if the set is empty.
set.remove( x)
Removes the element x from the set. If x doesn’t exist in the set, it raises error.
set.symmetric_difference( )
Performs symmetric difference and returns the set of all the members of the sets involved excluding the common elements.
set.union( x)
Performs  and the returns the union of the sets as a set.
set.update( )
Adds multiple items in the set.