- 0shares
- Facebook0
- Twitter0
- Google+0
- Pinterest0
- LinkedIn0

## Python Sets

In this section we will learn the sets in Python programming language. We will learn how the sets will be created and how we can remove elements from sets. In this section you will also learn the operations that can be performed on sets in Python.

A set can be defined as the unordered collection of items that are declared in curly brackets. The elements in a set should be unique that is they should not be repeated or duplicated. The elements of set should be immutable that is the elements of the set should not be changed.

But in Python the sets are mutable that is items or elements can be added or removed from a set. The mathematical operations like union, intersection, etc can be performed on sets.

### Creating a Set in Python

In Python a set can be creating by declaring or placing all the elements or items inside the curly brackets {}. The elements or items inside the set should be separated by a comma. We can also declare a set by using the python built in function that is set ().

A set can have a number of items of different data types that is we can place a number of integer data type, float data type, tuple or string etc in the set. As said earlier that the elements of the sets should be immutable, therefore, we cannot place a mutable element in the sets for example set cannot have list or dictionary or even another set as its element.

Consider the following example in which we have created a set and another set that have different elements of different data types:

**CODE**

>>> mySet = {1,2,3}

>>> print(mySet)

>>> mySet = {2.3, “Python”, (1,2,3)}

>>> print(mySet)

>>> mySet = {2.5, “Python”, [1,2,3]}

**OUTPUT**

{1, 2, 3}

{2.3, ‘Python’, (1, 2, 3)}

Traceback (most recent call last):

File “<pyshell#4>”, line 1, in <module>

mySet = {2.5, “Python”, [1,2,3]}

TypeError: unhashable type: ‘list’

In the above example, a set is declared at first which has only values that are of same data type and the elements are unique. Then another set is declared or created in which the elements or items of the set are of different data type. Then we created another set in which there are elements of different data types, but there is a list also as the element of the set and as the list is mutable therefore, an error is generated by the Python interpreter.

In Python we can create an empty set but if we write empty curly braces that is {} then the interpreter will create an empty dictionary in Python. To create an empty set in Python we can therefore, use the in-built function **set (). **Pass no arguments in the set () function to create an empty set in Python.

Consider the following example in which we have created an empty set using the set () function:

**CODE**

>>> x = {}

>>> print (type (x))

>>> x = set ()

>>> print (type (x))

**OUTPUT**

<class ‘dict’>

<class ‘set’>

In the above example, in the first line x is initialized with empty curly braces {}, when the class or type of this variable is checked we got class dict in the print statement using the type function. In this way we demonstrated that empty curly braces {} creates an empty dictionary in Python.

In the next lines x is initialized with the set () function hence an empty set is created. This was proved when we checked the class or data type of the variable x and the output we got is class set.

### Changing a Set in Python

A set in Python are mutable that is we can change the sets but the elements in the set are not in a definite order therefore indexing has no meanings for sets. The elements or items of the set cannot be accessed using indexing or slicing. Indexing and slicing is not supported by sets.

A single element in the set can be added by using the ‘**add ()**’ method. We can also add multiple elements in a set by using the **update ()** method. We can use the update () method with tuple, lists, strings, etc. The duplicated elements are avoided.

Consider the following example in which we have used the add () function to add a single element and update () function to add multiple elements in the set:

**CODE**

>>> mySet = {1, 3}

>>> mySet [1]

>>> mySet. add (2)

>>> print (mySet)

>>> mySet. update ([2, 3, 4])

>>> print (mySet)

>>> mySet. update ([4, 5], [1, 6, 7, 8])

>>> print (mySet)

**OUTPUT**

Traceback (most recent call last):

File “<pyshell#18>”, line 1, in <module>

mySet [1]

TypeError: ‘set’ object does not support indexing

{1, 2, 3}

{1, 2, 3, 4}

{1, 2, 3, 4, 5, 6, 7, 8}

In the above example, first line is declaring a set {1, 3}. When we tried to access an element of the set using indexing the interpreter generated an error. Then we used the add function to add an element to set. In the next lines update function is used to add multiple elements to the set.

### Removing Elements from a Set

In Python we can remove elements from a set by using the **discard ()** and **remove () **functions.

There is a slight difference between a discard () function and remove () function, when we use the discard () function if the particular item is not existing in the list then the list will remain unchanged. But when remove () function is used and if the particular element is not existing in the list then an error will be generated.

Consider the following example in which we have cleared the difference between discard () and remove () functions:

**CODE**

>>> mySet = {1, 2, 3, 4, 5}

>>> print(mySet)

>>> mySet.discard(3)

>>> print(mySet)

>>> mySet.remove(5)

>>> print(mySet)

>>> mySet.discard(3)

>>> print(mySet)

>>> mySet.remove(3)

**OUTPUT**

{1, 2, 3, 4, 5}

{1, 2, 4, 5}

{1, 2, 4}

{1, 2, 4}

Traceback (most recent call last):

File “<pyshell#27>”, line 1, in <module>

mySet.remove(3)

KeyError: 3

In the above example, a set is created then we discarded and removed elements from the set. We can see the difference between the discard () and remove () functions when an element which was not in the set is discarded the set remained unchanged but as soon as we used the remove () function to remove an element which was not in the set using the remove () function an error was generated by interpreter.

An item from a set can also be removed by using the pop () function. But we cannot determine that which element will be popped as the set is an unordered sequence of elements. To remove all the items from the set we can use the clear () function. This function does not delete the definition of the set from memory but it removes the items only.

Consider the following example in which we have done this:

**CODE**

>>> mySet = set (“PythonProgramming”)

>>> print (mySet)

>>> print (mySet. pop ())

>>> mySet. pop ()

>>> print (mySet)

>>> mySet. clear ()

>>> print (mySet)

**OUTPUT**

{‘n’, ‘o’, ‘r’, ‘a’, ‘t’, ‘m’, ‘i’, ‘P’, ‘h’, ‘y’, ‘g’}

n

‘o’

{‘r’, ‘a’, ‘t’, ‘m’, ‘i’, ‘P’, ‘h’, ‘y’, ‘g’}

set()

In the above example, a set is declared using the set function, then we used the pop () to pop a random element from the set. At last we cleared the list using the clear () function. When the set is printed an empty set is displayed on the output screen.

### Python Set Operation

We can use the mathematical set operations like union, intersection, difference, etc. These operations can be performed by using operators and methods.

Consider the following example in which there are two sets and we have to perform the union operation on it:

a = {1, 2, 3, 4, 5}

b = {5, 7, 8, 9, 10}

### Set Union

The union of two sets means a set of all the elements from both of the sets. Consider the following diagram and you will understand the concept of the union operation:

In Python the union operation can be performed by using the (|) operator. We can also perform the union operation by using the built in function that is union ().

Consider the following example in which the union function is performed on two sets:

**CODE**

>>> a= {1, 2, 3, 4, 5}

>>> b={6, 7, 8, 9, 10}

>>> print (a | b)

**OUTPUT**

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Consider the following example in which the built in union function is used to perform the union function:

**CODE**

>>> a= {1, 2, 3, 4, 5}

>>> b={6, 7, 8, 9, 10}

>>> print (a | b)

>>> a. union (b)

>>> b. union (a)

**OUTPUT**

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

### Set Intersection

The intersection of two sets means a set of all the common elements from both of the sets. Consider the following diagram and you will understand the concept of the intersection operation:

In Python the intersection operation can be by using the (&) operator. We can also use the built in intersection () function to perform the intersection operation in Python programming.

Consider the following example in which two sets are declared and intersection operation is performed by using the (&) operator.

**CODE**

>>> a = {1, 2, 3, 4, 5}

>>> b = {4, 5, 6, 2, 7}

>>> print (a & b)

**OUTPUT**

{2, 4, 5}

Now consider the following example in which the intersection is performed by the built in intersection () function:

**CODE**

>>> a = {1, 2, 3, 4, 5}

>>> b = {4, 5, 6, 2, 7}

>>> print (a & b)

>>> a. intersection (b)

>>> b. intersection (a)

**OUTPUT**

{2, 4, 5}

{2, 4, 5}

{2, 4, 5}

### Set Difference

The difference of two sets means a set of elements that are in set ‘a’ but not in the set ‘b’ equivalent to (a-b). Consider the following diagram and you will understand the concept of the set difference:

The set operation in Python can be performed by the minus operator (-). The set (b-a) means all the elements that are in set ‘b’ but not present in set ‘a’.

The set difference in Python can be performed by using the built in function difference ().

Consider the following example in which we will be finding the difference of two sets:

**CODE**

>>> a = {1, 2, 3, 4, 5}

>>> b = {2, 4, 7, 3, 8}

>>> print (a-b)

**OUTPUT**

{1, 5}

Consider the following example in which (b-a) is performed:

**CODE**

>>> a = {1, 2, 3, 4, 5}

>>> b = {2, 4, 7, 3, 8}

>>> print (b-a)

**OUTPUT**

{8, 7}

This printed the elements that are present in the set ‘b’ and are not present in the set ‘a’.

Now consider the following example in which the built in function difference () is used to perform difference of two sets:

**CODE**

>>> a = {1, 2, 3, 4, 5}

>>> b = {2, 4, 7, 3, 8}

>>> print (a-b)

>>> print (b-a)

>>> a. difference (b)

>>> b. difference (a)

**OUTPUT**

{1, 5}

{8, 7}

{1, 5}

{8, 7}

### Set Symmetric Difference

By symmetric difference of two sets we mean the elements of both of the sets accept those elements that are common. Consider the following diagram and you will understand the concept of symmetric difference of elements:

The symmetric operation in Python can be performed by using the ^ operator. We can also use the built in function that is symmetric_difference ().

Consider the following example in which we have used the ^ operator to perform the symmetric difference operation:

**CODE**

>>> a = {1, 2, 3, 4, 5}

>>> b = {3, 4, 7, 8, 6}

>>> print (a ^ b)

**OUTPUT**

{1, 2, 5, 6, 7, 8}

Now consider the following example in which we have used the built in symmetric_difference () function to perform the respective operation:

**CODE**

>>> a = {1, 2, 3, 4, 5}

>>> b = {3, 4, 7, 8, 6}

>>> print (a ^ b)

>>> a. symmetric_difference (b)

>>> b. symmetric_difference (a)

**OUTPUT**

{1, 2, 5, 6, 7, 8}

{1, 2, 5, 6, 7, 8}

{1, 2, 5, 6, 7, 8}

## Python Set Methods

In Python there a number of set functions. Consider the following table in which various set methods are described:

Methods |
Description |

add () | This method is used to add or insert a new element into a set. |

clear () | This method is used to clear the set or remove all the elements from a set. The set is not deleted but becomes an empty set. |

copy () | This method is used to return a new copy of already existing set. |

difference () | This method is used to return the difference of two or more sets in Python. |

difference_update () | This method is used to remove all the elements of some other set from a particular set. |

discard () | This method is used to remove an item or element from a set; if that item does not exist in the set the set will remain unchangeable. |

intersection () | This method is used to return the intersection of two sets by creating a new set. |

intersection_update () | This method is used to update a set with the intersection of the particular set with another set. |

isdisjoint () | This method is used to return a True if the intersection of two cells is a NULL set. |

issubset () | This method is used to return true if some other set is the subset of the set provided by the user. By subset we mean that if some other set contains this set. |

pop () | This method is used to return and remove a random number from a set, if the set is empty it raises an error that is key error. |

remove () | This method is used to remove or delete an element from a set. If the particular element is not in the set then an error will be generated. |

symmetric_difference () | This method is used to return the symmetric difference of two sets in the form of a new set. |

union () | This method is used to return the union of two sets in the form of a new set. |

update () | This method is used to update a particular set by taking the union of that set and other sets. |

### Other set operations

### Set Membership Test

In Python we can test an item in the set by using the keyword **in. **By testing an item in the set we mean that if the item exists in the set or not.

Consider the following example in which we have declared a set and checked if any item of the set exists in the declared set or not by using the in keyword Python:

**CODE**

>>> mySet = set (“PythonProgramming”)

>>> print (‘p’ in mySet)

>>> print (‘P’ in mySet)

**OUTPUT**

False

True

In the above example in the first statement a set has been declared using the set () function then we checked small p that if it exists in the set or not and got false because Python is a case sensitive language and can distinguish between small p and capital p. Therefore in the second statement we got true in the output because capital P was checked to be in the set “Python Programming” by using the in keyword.

### Iterating through a Set

In Python we can iterate through each item of the set by using the ‘for statement’. Consider the following example in which we have used the ‘for statement’ to iterate through the items of the set:

**CODE**

>>> for a in set(“PythonProgramming”):

print(a)

**OUTPUT**

n

o

r

a

t

m

i

P

h

y

g

In the above example for loop is used to iterate through the elements of the set. The set is created by the built in set function. The counter variable ‘a’ iterates through the each element of the set and then this variable is printed using the print statement and all the items of the set are printed because a iterated through the elements of the set.

### Built in Functions with Sets

There are a lot of function that are built in to be performed on sets in Python for example all (), enumerate (), len (), max (), sum (), etc. Consider the following table in which the built in set operations are listed and are described:

Function |
Description |

all () | This function is used to return a true if all the elements in the set are true and if the set is empty. |

any () | This function is used to return a true if any of the elements in the set are true and returns a false if the set is empty. |

enumerate () | This function is used to return an enumerate object. The enumerate function has the index and the value of all the items of the set as a pair. |

len () | This function is used to return the length of the set or the number of the elements in the set. |

max () | This function is used to return the largest item in the set. |

min () | This function is used to return the smallest item of the set. |

sorted () | This function is used to a new sorted set. The sorted () function does not sort the set itself but it returns the already sorted set. |

sum () | This function is used to return the sum of all the elements in the set. |

### Python Frozenset

A frozenset is considered to be a new class which has the abilities of a set. The difference between a frozen set and a simple set is that the items or elements in the frozen set cannot be changed once we have declared them. Just like we can say that a tuple is an immutable list likewise frozen set is an immutable set.

A set cannot be used as dictionary key because the sets are mutable or we can say that the sets are unhashable. The frozen sets are hashable and they can also be used as the keys for the Python dictionary.

In Python the frozen set can be created by using the built in frozenset () function. The frozenset supports the following built in methods of Python:

This method is used to return a new copy of already existing frozenset.

This method is used to return the difference of two or more frozensets in Python.

This method is used to return the intersection of two sets by creating a new frozenset.

This method is used to return a True if the intersection of two cells is a NULL frozenset.

This method is used to return true if some other frozenset is the subset of the frozenset provided by the user. By subset we mean that if some other frozenset contains this frozenset.

This method is used to return true if some other frozenset is the superset of the frozenset provided by the user.

This method is used to return the symmetric difference of two frozensets in the form of a new frozenset.

This method is used to return the union of two frozensets in the form of a new frozenset.

As the frozenset is immutable therefore, we cannot apply the ‘add’ or ‘remove’ functions to add an element in the set or to remove an element from the set.

Consider the following example in which we have only initialized two frozensets.

**CODE**

a = frozenset ([1, 2, 3, 4])

b = frozenset ([3, 4, 5, 7])

Consider the following example in which we have used the built in functions with the frozensets:

**CODE**

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

>>> b = frozenset ([3, 4, 5, 7])

>>> a. isdisjoint (b)

>>> a. difference (b)

>>> a | b

>>> a.add (2)

**OUTPUT**

False

frozenset ({1, 2})

frozenset ({1, 2, 3, 4, 5, 7})

Traceback (most recent call last):

File “<pyshell#75>”, line 1, in <module>

a.add (2)

AttributeError: ‘frozenset’ object has no attribute ‘add’

In the above example two frozensets are initialized then we used the isdisjoint function. Then we found the union of the two sets. When we tried to add an element to the frozenset an error is generated because we cannot add or remove elements from a frozenset.