The set in python can be defined as the unordered collection of various items enclosed within the curly braces. The elements of the set can not be duplicate. The elements of the python set must be immutable.

Unlike other collections in python, there is no index attached to the elements of the set, i.e., we cannot directly access any element of the set by the index. However, we can print them all together or we can get the list of elements by looping through the set.

The set can be created by enclosing the comma separated items with the curly braces. Python also provides the set method which can be used to create the set by the passed sequence.

snippet

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"} print(Days) print(type(Days)) print("looping through the set elements ... ") for i in Days: print(i)

**Output:**

Output

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday

snippet

Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]) print(Days) print(type(Days)) print("looping through the set elements ... ") for i in Days: print(i)

**Output:**

Output

{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}
<class 'set'>
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday

In the previous example, we have discussed about how the set is created in python. However, we can perform various mathematical operations on python sets like union, intersection, difference, etc.

Python provides the add() method which can be used to add some particular item to the set. Consider the following example.

snippet

Months = set(["January","February", "March", "April", "May", "June"]) print("\nprinting the original set ... ") print(Months) print("\nAdding other months to the set..."); Months.add("July"); Months.add("August"); print("\nPrinting the modified set..."); print(Months) print("\nlooping through the set elements ... ") for i in Months: print(i)

**Output:**

Output

printing the original set ...
{'February', 'May', 'April', 'March', 'June', 'January'}
Adding other months to the set...
Printing the modified set...
{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}
looping through the set elements ...
February
July
May
April
March
August
June
January

To add more than one item in the set, Python provides the **update()** method.

Consider the following example.

snippet

Months = set(["January","February", "March", "April", "May", "June"]) print("\nprinting the original set ... ") print(Months) print("\nupdating the original set ... ") Months.update(["July","August","September","October"]); print("\nprinting the modified set ... ") print(Months);

**Output:**

Output

printing the original set ...
{'January', 'February', 'April', 'May', 'June', 'March'}
updating the original set ...
printing the modified set ...
{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}

Python provides **discard()** method which can be used to remove the items from the set.

Consider the following example.

snippet

Months = set(["January","February", "March", "April", "May", "June"]) print("\nprinting the original set ... ") print(Months) print("\nRemoving some months from the set..."); Months.discard("January"); Months.discard("May"); print("\nPrinting the modified set..."); print(Months) print("\nlooping through the set elements ... ") for i in Months: print(i)

**Output:**

Output

printing the original set ...
{'February', 'January', 'March', 'April', 'June', 'May'}
Removing some months from the set...
Printing the modified set...
{'February', 'March', 'April', 'June'}
looping through the set elements ...
February
March
April
June

Python also provide the remove() method to remove the items from the set. Consider the following example to remove the items using remove() method.

snippet

Months = set(["January","February", "March", "April", "May", "June"]) print("\nprinting the original set ... ") print(Months) print("\nRemoving some months from the set..."); Months.remove("January"); Months.remove("May"); print("\nPrinting the modified set..."); print(Months)

**Output:**

Output

printing the original set ...
{'February', 'June', 'April', 'May', 'January', 'March'}
Removing some months from the set...
Printing the modified set...
{'February', 'June', 'April', 'March'}

We can also use the pop() method to remove the item. However, this method will always remove the last item.

Consider the following example to remove the last item from the set.

snippet

Months = set(["January","February", "March", "April", "May", "June"]) print("\nprinting the original set ... ") print(Months) print("\nRemoving some months from the set..."); Months.pop(); Months.pop(); print("\nPrinting the modified set..."); print(Months)

**Output:**

Output

printing the original set ...
{'June', 'January', 'May', 'April', 'February', 'March'}
Removing some months from the set...
Printing the modified set...
{'May', 'April', 'February', 'March'}

Python provides the clear() method to remove all the items from the set.

Consider the following example.

snippet

Months = set(["January","February", "March", "April", "May", "June"]) print("\nprinting the original set ... ") print(Months) print("\nRemoving all the items from the set..."); Months.clear() print("\nPrinting the modified set...") print(Months)

**Output:**

Output

printing the original set ...
{'January', 'May', 'June', 'April', 'March', 'February'}
Removing all the items from the set...
Printing the modified set...
set()

Despite the fact that discard() and remove() method both perform the same task, There is one main difference between discard() and remove().

If the key to be deleted from the set using discard() doesn't exist in the set, the python will not give the error. The program maintains its control flow.

On the other hand, if the item to be deleted from the set using remove() doesn't exist in the set, the python will give the error.

Consider the following example.

snippet

Months = set(["January","February", "March", "April", "May", "June"]) print("\nprinting the original set ... ") print(Months) print("\nRemoving items through discard() method..."); Months.discard("Feb"); #will not give an error although the key feb is not available in the set print("\nprinting the modified set...") print(Months) print("\nRemoving items through remove() method..."); Months.remove("Jan") #will give an error as the key jan is not available in the set. print("\nPrinting the modified set...") print(Months)

**Output:**

Output

printing the original set ...
{'March', 'January', 'April', 'June', 'February', 'May'}
Removing items through discard() method...
printing the modified set...
{'March', 'January', 'April', 'June', 'February', 'May'}
Removing items through remove() method...
Traceback (most recent call last):
File "set.py", line 9, in
Months.remove("Jan")
KeyError: 'Jan'

The union of two sets are calculated by using the or (|) operator. The union of the two sets contains the all the items that are present in both the sets.

Consider the following example to calculate the union of two sets.

snippet

Days1 = {"Monday","Tuesday","Wednesday","Thursday"} Days2 = {"Friday","Saturday","Sunday"} print(Days1|Days2) #printing the union of the sets

**Output:**

Output

{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'}

Python also provides the **union()** method which can also be used to calculate the union of two sets. Consider the following example.

snippet

Days1 = {"Monday","Tuesday","Wednesday","Thursday"} Days2 = {"Friday","Saturday","Sunday"} print(Days1.union(Days2)) #printing the union of the sets

**Output:**

Output

{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday', 'Saturday'}

The & (intersection) operator is used to calculate the intersection of the two sets in python. The intersection of the two sets are given as the set of the elements that common in both sets.

Consider the following example.

snippet

set1 = {"Ayush","John", "David", "Martin"} set2 = {"Steve","Milan","David", "Martin"} print(set1&set2) #prints the intersection of the two sets

**Output:**

Output

{'Martin', 'David'}

snippet

set1 = {"Ayush","John", "David", "Martin"} set2 = {"Steave","Milan","David", "Martin"} print(set1.intersection(set2)) #prints the intersection of the two sets

**Output:**

Output

{'Martin', 'David'}

The intersection_update() method removes the items from the original set that are not present in both the sets (all the sets if more than one are specified).

The Intersection_update() method is different from intersection() method since it modifies the original set by removing the unwanted items, on the other hand, intersection() method returns a new set.

Consider the following example.

snippet

a = {"ayush", "bob", "castle"} b = {"castle", "dude", "emyway"} c = {"fuson", "gaurav", "castle"} a.intersection_update(b, c) print(a)

**Output:**

Output

{'castle'}

The difference of two sets can be calculated by using the subtraction (-) operator. The resulting set will be obtained by removing all the elements from set 1 that are present in set 2.

Consider the following example.

snippet

Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"} Days2 = {"Monday", "Tuesday", "Sunday"} print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}

**Output:**

Output

{'Thursday', 'Wednesday'}

snippet

Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"} Days2 = {"Monday", "Tuesday", "Sunday"} print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2

**Output:**

Output

{'Thursday', 'Wednesday'}

Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by using which we can check whether a set is subset, superset, or equivalent to other set. The boolean true or false is returned depending upon the items present inside the sets.

Consider the following example.

snippet

Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"} Days2 = {"Monday", "Tuesday"} Days3 = {"Monday", "Tuesday", "Friday"} #Days1 is the superset of Days2 hence it will print true. print (Days1>Days2) #prints false since Days1 is not the subset of Days2 print (Days1

**Output:**

Output

True
False
False

The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set can not be changed and therefore it can be used as a key in dictionary.

The elements of the frozen set can not be changed after the creation. We cannot change or append the content of the frozen sets by using the methods like add() or remove().

The frozenset() method is used to create the frozenset object. The iterable sequence is passed into this method which is converted into the frozen set as a return type of the method.

Consider the following example to create the frozen set.

snippet

Frozenset = frozenset([1,2,3,4,5]) print(type(Frozenset)) print("\nprinting the content of frozen set...") for i in Frozenset: print(i); Frozenset.add(6) #gives an error since we cannot change the content of Frozenset after creation

**Output:**

Output

<class 'frozenset'>
printing the content of frozen set...
1
2
3
4
5
Traceback (most recent call last):
File "set.py", line 6, in <module>
Frozenset.add(6) #gives an error since we can change the content of Frozenset after creation
AttributeError: 'frozenset' object has no attribute 'add'

If we pass the dictionary as the sequence inside the frozenset() method, it will take only the keys from the dictionary and returns a frozenset that contains the key of the dictionary as its elements.

Consider the following example.

snippet

Dictionary = {"Name":"John", "Country":"USA", "ID":101} print(type(Dictionary)) Frozenset = frozenset(Dictionary); #Frozenset will contain the keys of the dictionary print(type(Frozenset)) for i in Frozenset: print(i)

**Output:**

Output

<class 'dict'>
<class 'frozenset'>
Name
Country
ID

Python contains the following methods to be used with the sets.

SN | Method | Description |
---|---|---|

1 | add(item) | It adds an item to the set. It has no effect if the item is already present in the set. |

2 | clear() | It deletes all the items from the set. |

3 | copy() | It returns a shallow copy of the set. |

4 | difference_update(....) | It modifies this set by removing all the items that are also present in the specified sets. |

5 | discard(item) | It removes the specified item from the set. |

6 | intersection() | It returns a new set that contains only the common elements of both the sets. (all the sets if more than two are specified). |

7 | intersection_update(....) | It removes the items from the original set that are not present in both the sets (all the sets if more than one are specified). |

8 | Isdisjoint(....) | Return True if two sets have a null intersection. |

9 | Issubset(....) | Report whether another set contains this set. |

10 | Issuperset(....) | Report whether this set contains another set. |

11 | pop() | Remove and return an arbitrary set element that is the last element of the set. Raises KeyError if the set is empty. |

12 | remove(item) | Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. |

13 | symmetric_difference(....) | Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. |

14 | symmetric_difference_update(....) | Update a set with the symmetric difference of itself and another. |

15 | union(....) | Return the union of sets as a new set. (i.e. all elements that are in either set.) |

16 | update() | Update a set with the union of itself and others. |

Related Tutorial

1
Pass

7
File I/O

10
Regex

16
Assert

19
Math Module

20
OS Module

25
IDEs

26
Arrays

28
Magic Method

31
Decorator

32
Generators

34
Python JSON