Python Sets
What is a set in Python?
A set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc.
How to create a set?
A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the built-in function set()
.
It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have a mutable element, like list, set or dictionary, as its element.
Try the following examples as well.
Creating an empty set is a bit tricky.
Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements we use the set()
 function without any argument.
How to change a set in Python?
Sets are mutable. But since they are unordered, indexing have no meaning.
We cannot access or change an element of set using indexing or slicing. Set does not support it.
We can add single element using the add()
 method and multiple elements using the update()
 method. The update()
 method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.
When you run the program, the output will be:
{1, 3} {1, 2, 3} {1, 2, 3, 4} {1, 2, 3, 4, 5, 6, 8}
How to remove elements from a set?
A particular item can be removed from set using methods, discard()
 and remove()
.
The only difference between the two is that, while using discard()
 if the item does not exist in the set, it remains unchanged. But remove()
 will raise an error in such condition.
The following example will illustrate this.
pop()
 method.Set being unordered, there is no way of determining which item will be popped. It is completely arbitrary.
We can also remove all items from a set using clear()
.
Python Set Operations
Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference. We can do this with operators or methods.
Let us consider the following two sets for the following operations.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
Union of A and B is a set of all elements from both sets.
Union is performed using |
 operator. Same can be accomplished using the method union()
.
# use union function
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}
# use union function on B
>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}
Set Intersection
Intersection of A and B is a set of elements that are common in both sets.
Intersection is performed using &
 operator. Same can be accomplished using the method intersection()
.
# use intersection function on A
>>> A.intersection(B)
{4, 5}
# use intersection function on B
>>> B.intersection(A)
{4, 5}
Set Difference
Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a set of element in B but not in A.
Difference is performed using -
 operator. Same can be accomplished using the method difference()
.
# use difference function on A
>>> A.difference(B)
{1, 2, 3}
# use - operator on B
>>> B - A
{8, 6, 7}
# use difference function on B
>>> B.difference(A)
{8, 6, 7}
Set Symmetric Difference
Symmetric Difference of A and B is a set of elements in both A and B except those that are common in both.
Symmetric difference is performed using ^
 operator. Same can be accomplished using the method symmetric_difference()
.
Try the following examples on Python shell.
# use symmetric_difference function on A
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
# use symmetric_difference function on B
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}
Different Python Set Methods
There are many set methods, some of which we have already used above. Here is a list of all the methods that are available with set objects.
Method | Description |
---|---|
add() | Adds an element to the set |
clear() | Removes all elements from the set |
copy() | Returns a copy of the set |
difference() | Returns the difference of two or more sets as a new set |
difference_update() | Removes all elements of another set from this set |
discard() | Removes an element from the set if it is a member. (Do nothing if the element is not in set) |
intersection() | Returns the intersection of two sets as a new set |
intersection_update() | Updates the set with the intersection of itself and another |
isdisjoint() | Returns True  if two sets have a null intersection |
issubset() | Returns True  if another set contains this set |
issuperset() | Returns True  if this set contains another set |
pop() | Removes and returns an arbitary set element. Raise KeyError  if the set is empty |
remove() | Removes an element from the set. If the element is not a member, raise a KeyError |
symmetric_difference() | Returns the symmetric difference of two sets as a new set |
symmetric_difference_update() | Updates a set with the symmetric difference of itself and another |
union() | Returns the union of sets in a new set |
update() | Updates the set with the union of itself and others |
Other Set Operations
Set Membership Test
We can test if an item exists in a set or not, using the keyword in.
Iterating Through a Set
Using a for loop, we can iterate though each item in a set.
>>> for letter in set("apple"):
... print(letter)
...
Built-in Functions with Set
Built-in functions like all()
, any()
, enumerate()
, len()
, max()
, min()
, sorted()
, sum()
 etc. are commonly used with set to perform different tasks.
Function | Description |
---|---|
all() | Return True  if all elements of the set are true (or if the set is empty). |
any() | Return True  if any element of the set is true. If the set is empty, return False. |
enumerate() | Return an enumerate object. It contains the index and value of all the items of set as a pair. |
len() | Return the length (the number of items) in the set. |
max() | Return the largest item in the set. |
min() | Return the smallest item in the set. |
sorted() | Return a new sorted list from elements in the set(does not sort the set itself). |
sum() | Retrun the sum of all elements in the set. |
Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. While tuples are immutable lists, frozensets are immutable sets.
Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand, frozensets are hashable and can be used as keys to a dictionary.
Frozensets can be created using the function frozenset().
This datatype supports methods like copy()
, difference()
, intersection()
, isdisjoint()
, issubset()
, issuperset()
, symmetric_difference()
 and union()
. Being immutable it does not have method that add or remove elements.
Try these examples on Python shell.
>>> A.isdisjoint(B)
False
>>> A.difference(B)
frozenset({1, 2})
>>> A | B
frozenset({1, 2, 3, 4, 5, 6})
>>> A.add(3)
...
AttributeError: 'frozenset' object has no attribute 'add'
Python Sets
Set
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Note:Â Sets are unordered, so you cannot be sure in which order the items will appear.
Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
But you can loop through the set items using a for
 loop, or ask if a specified value is present in a set, by using the in
 keyword.
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana"Â in thisset)
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add one item to a set use the add()
 method.
To add more than one item to a set use the update()
 method.
Example
Add an item to a set, using the add()
 method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Example
Add multiple items to a set, using the update()
 method:
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset
Get the Length of a Set
To determine how many items a set has, use the len()
 method.
Example
Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Remove Item
To remove an item in a set, use the remove()
, or the discard()
 method.
Example
Remove "banana" by using the remove()
 method:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
Note: If the item to remove does not exist, remove()
 will raise an error.
Example
Remove "banana" by using the discard()
 method:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
Note: If the item to remove does not exist, discard()
 will NOT raise an error.
You can also use the pop()
, method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed.
The return value of the pop()
 method is the removed item.
Example
Remove the last item by using the pop()
 method:
thisset = {"apple", "banana", "cherry"}
x =Â thisset.pop()
print(x)
print(thisset)
Note: Sets are unordered, so when using the pop()
 method, you will not know which item that gets removed.
Example
The clear()
 method empties the set:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
Example
The del
 keyword will delete the set completely:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
The set() Constructor
It is also possible to use the set() constructor to make a set.
Example
Using the set() constructor to make a set:
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)
Set Methods
Python has a set of built-in methods that you can use on sets.
Method | Description |
---|---|
add() | Adds an element to the set |
clear() | Removes all the elements from the set |
copy() | Returns a copy of the set |
difference() | Returns a set containing the difference between two or more sets |
difference_update() | Removes the items in this set that are also included in another, specified set |
discard() | Remove the specified item |
intersection() | Returns a set, that is the intersection of two other sets |
intersection_update() | Removes the items in this set that are not present in other, specified set(s) |
isdisjoint() | Returns whether two sets have a intersection or not |
issubset() | Returns whether another set contains this set or not |
issuperset() | Returns whether this set contains another set or not |
pop() | Removes an element from the set |
remove() | Removes the specified element |
symmetric_difference() | Returns a set with the symmetric differences of two sets |
symmetric_difference_update() | inserts the symmetric differences from this set and another |
union() | Return a set containing the union of sets |
update() | Update the set with the union of this set and others |
#####################################################
s={1,2,3,4}
t={6,7,3}
x={3,7,6}
print(s)
# Itrerator
for ele in s:
print(ele)
s.add(6)
s.add(3.5)
print(s)
s.discard(6)
print(s)
# Union
print(s|t)
# Intersection
print(s&t)
# Set Equal
print(s==t)
#
print(x==t)
# Set Difference
print(s-t)
# Super Set
print(t>=x)
# sub Set
print(t<x)
######################################