Introduction to Python Sets

If you are interested to learn about the Python Date/time

What is Set?

Sets are used to store multiple items in a single variable. Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are ListTuple, and Dictionary, all with different qualities and usage. A Set is an unordered collection data type that is inerrable, mutable and has no duplicate elements. Python’s set class represents the mathematical notion of a set. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a hash table. Since sets are unordered, we cannot access items using indexes like we do in lists. A set is a collection which is unorderedunchangeable*, and unindexed.

* Note: Set items are unchangeable, but you can remove items and add new items.

Sets are written with curly brackets.

myset = {"apple", "banana", "cherry"}


Create a Set:thisset = {"apple", "banana", "cherry"}<br>print(thisset)

Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.


Unordered means that the items in a set do not have a defined order. Set items can appear in a different order every time you use them, and cannot be referred to by index or key.


Set items are unchangeable, meaning that we cannot change the items after the set has been created. Once a set is created, you cannot change its items, but you can remove items and add new items.

Duplicates Not Allowed

Sets cannot have two items with the same value.


Duplicate values will be ignored:

thisset = {"apple", "banana", "cherry", "apple"}

Get the Length of a Set

To determine how many items a set has, use the len() function.


Get the number of items in a set:

thisset = {"apple", "banana", "cherry"} print(len(thisset))

Set Items – Data Types

Set items can be of any data type:


String, int and boolean data types:

set1 = {"apple", "banana", "cherry"}<br>set2 = {1, 5, 7, 9, 3}<br>set3 = {True, False, False}

A set can contain different data types:


A set with strings, integers and boolean values:set1 = {"abc", 34, True, 40, "male"}


From Python’s perspective, sets are defined as objects with the data type ‘set’:<class ‘set’>


What is the data type of a set?

myset = {"apple", "banana", "cherry"}<br>print(type(myset))

The set() Constructor

It is also possible to use the set() constructor to make a set.


Using the set() constructor to make a set:

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets<br>print(thisset)

Python Collections (Arrays)

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered** and changeable. No duplicate members.

Python – Access Set Items

Access Items

You cannot access items in a set by referring to an index or a key. 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.


Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"} for x in thisset:<br>  print(x)


Check if “banana” is present in the set:

thisset = {"apple", "banana", "cherry"} print("banana" in thisset)

Python – Add Set Items

Add Items

Once a set is created, you cannot change its items, but you can add new items. To add one item to a set use the add() method.


Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"} thisset.add("orange") print(thisset)

Add Sets

To add items from another set into the current set, use the update() method.


Add elements from tropical into thisset:

thisset = {"apple", "banana", "cherry"}<br>tropical = {"pineapple", "mango", "papaya"} thisset.update(tropical) print(thisset)

Add Any Iterable

The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.).


Add elements of a list to at set:

thisset = {"apple", "banana", "cherry"}<br>mylist = ["kiwi", "orange"] thisset.update(mylist) rint(thisset)

Python – Remove Set Items

Remove Item

To remove an item in a set, use the remove(), or the discard() method.


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.


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.


thisset = {"apple", "banana", "cherry"} x = thisset.pop() print(x) print(thisset)

Note: Sets are unordered, so when using the pop() method, you do not know which item that gets removed.


The clear() method empties the set:

thisset = {"apple", "banana", "cherry"} thisset.clear() print(thisset)


The del keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"} del thisset print(thisset)

Python – Loop Sets

Loop Items

You can loop through the set items by using a for loop:


Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"} for x in thisset:<br>  print(x)

Python – Join Sets

Join Two Sets

There are several ways to join two or more sets in Python. You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another:


The union() method returns a new set with all items from both sets:

set1 = {"a", "b" , "c"}<br>set2 = {1, 2, 3} set3 = set1.union(set2)<br>print(set3)


The update() method inserts the items in set2 into set1:

set1 = {"a", "b" , "c"}<br>set2 = {1, 2, 3}

Internal working of Set

This is based on a data structure known as a hash table
If Multiple values are present at the same index position, then the value is appended to that index position, to form a Linked List. In, Python Sets are implemented using dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity.
Set Implementation:-

Sets with Numerous operations on a single HashTable:-

Methods for Sets

Adding elements

Insertion in set is done through set.add() function, where an appropriate record value is created to store in the hash table. Same as checking for an item, i.e., O(1) on average. However, in worst case it can become O(n).

  • Python3
# A Python program to# demonstrate adding elements# in a set # Creating a Setpeople = {"Jay", "Idrish", "Archi"} print("People:", end = " ")print(people) # This will add Daxit# in the setpeople.add("Daxit") # Adding elements to the# set using iteratorfor i in range(1, 6):people.add(i) print("\nSet after adding element:", end = " ")print(people)


People: {'Idrish', 'Archi', 'Jay'}

Set after adding element: {1, 2, 3, 4, 5, 'Idrish', 'Archi', 'Jay', 'Daxit'}

Operators for Sets

Sets and frozen sets support the following operators:

key in scontainment check
key not in snon-containment check
s1 == s2s1 is equivalent to s2
s1 != s2s1 is not equivalent to s2
s1 <= s2s1 is subset of s2
s1 < s2s1 is proper subset of s2
s1 >= s2s1 is superset of s2
s1 > s2s1 is proper superset of s2
s1 | s2the union of s1 and s2
s1 & s2the intersection of s1 and s2
s1 – s2the set of elements in s1 but not s2
s1 ˆ s2the set of elements in precisely one of s1 or s2

Code Snippet to illustrate all Set operations in Python 

  • Python
# Python program to demonstrate working# of# Set in Python # Creating two setsset1 = set()set2 = set() # Adding elements to set1for i in range(1, 6):set1.add(i) # Adding elements to set2for i in range(3, 8):set2.add(i) print("Set1 = ", set1)print("Set2 = ", set2)print("\n") # Union of set1 and set2set3 = set1 | set2# set1.union(set2)print("Union of Set1 & Set2: Set3 = ", set3) # Intersection of set1 and set2set4 = set1 & set2# set1.intersection(set2)print("Intersection of Set1 & Set2: Set4 = ", set4)print("\n") # Checking relation between set3 and set4if set3 > set4: # set3.issuperset(set4)print("Set3 is superset of Set4")else if set3 < set4: # set3.issubset(set4)print("Set3 is subset of Set4")else : # set3 == set4print("Set3 is same as Set4") # displaying relation between set4 and set3if set4 < set3: # set4.issubset(set3)print("Set4 is subset of Set3")print("\n") # difference between set3 and set4set5 = set3 - set4print("Elements in Set3 and not in Set4: Set5 = ", set5)print("\n") # check if set4 and set5 are disjoint setsif set4.isdisjoint(set5):print("Set4 and Set5 have nothing in common\n") # Removing all the values of set5set5.clear() print("After applying clear on sets Set5: ")print("Set5 = ", set5)


('Set1 = ', set([1, 2, 3, 4, 5]))
('Set2 = ', set([3, 4, 5, 6, 7]))

('Union of Set1 & Set2: Set3 = ', set([1, 2, 3, 4, 5, 6, 7]))
('Intersection of Set1 & Set2: Set4 = ', set([3, 4, 5]))

Set3 is superset of Set4
Set4 is subset of Set3

('Elements in Set3 and not in Set4: Set5 = ', set([1, 2, 6, 7]))

Set4 and Set5 have nothing in common

After applying clear on sets Set5: 
('Set5 = ', set([]))

Time complexity of Sets

OperationAverage caseWorst Casenotes
x in sO(1)O(n) 
Union s|tO(len(s)+len(t))  
Intersection s&tO(min(len(s), len(t))O(len(s) * len(t))replace “min” with “max” if t is not a set
Multiple intersection s1&s2&..&sn (n-1)*O(l) where l is max(len(s1),..,len(sn)) 
Difference s-tO(len(s)) 

Introduction to Python Sets
Show Buttons
Hide Buttons