top of page

Python Sets

Updated: May 20, 2023

Topic List :

A set is a collection of unique data. That is, elements of a set cannot be duplicate. For example, Suppose we want to store information about student IDs. Since student IDs cannot be duplicate, we can use a set.

Create a Set in Python

In Python, we create sets by placing all the elements inside curly braces {}, separated by comma.

A set can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.

Let's see an example,

# create a set of integer type
student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)

# create a set of string type
vowel_letters = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowel_letters)

# create a set of mixed data types
mixed_set = {'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)


Student ID: {112, 114, 115, 116, 118}
Vowel Letters: {'u', 'a', 'e', 'i', 'o'}
Set of mixed data types: {'Hello', 'Bye', 101, -2}

In the above example, we have created different types of sets by placing all the elements inside the curly braces {}.

Note: When you run this code, you might get output in a different order. This is because the set has no particular order.

Create an Empty Set in Python

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. For example,

# create an empty set
empty_set = set()

# create an empty dictionary
empty_dictionary = { }

# check data type of empty_set
print('Data type of empty_set:', type(empty_set))

# check data type of dictionary_set
print('Data type of empty_dictionary', type(empty_dictionary))


Data type of empty_set: <class 'set'>
Data type of empty_dictionary <class 'dict'>


  • empty_set - an empty set created using set()

  • empty_dictionary - an empty dictionary created using {}

Finally we have used the type() function to know which class empty_set and empty_dictionary belong to.

Duplicate Items in a Set

Let's see what will happen if we try to include duplicate items in a set.

numbers = {2, 4, 6, 6, 2, 8} 
print(numbers)   # {8, 2, 4, 6}

Here, we can see there are no duplicate items in the set as a set cannot contain duplicates.

Add and Update Set Items in Python

Sets are mutable. However, since they are unordered, indexing has no meaning.

We cannot access or change an element of a set using indexing or slicing. Set data type does not support it.

Add Items to a Set in Python

In Python, we use the add() method to add an item to a set. For example,

numbers = {21, 34, 54, 12}

print('Initial Set:',numbers)

# using add() method

print('Updated Set:', numbers) 


Initial Set: {34, 12, 21, 54}
Updated Set: {32, 34, 12, 21, 54}

In the above example, we have created a set named numbers. Notice the line,


Here, add() adds 32 to our set.

Update Python Set

The update() method is used to update the set with items other collection types (lists, tuples, sets, etc). For example,

companies = {'Lacoste', 'Ralph Lauren'}
tech_companies = ['apple', 'google', 'apple']



# Output: {'google', 'apple', 'Lacoste', 'Ralph Lauren'}

Here, all the unique elements of tech_companies are added to the companies set.

Remove an Element from a Set

We use the discard() method to remove the specified element from a set. For example,

languages = {'Swift', 'Java', 'Python'}

print('Initial Set:',languages)

# remove 'Java' from a set
removedValue = languages.discard('Java')

print('Set after remove():', languages)


Initial Set: {'Python', 'Swift', 'Java'}
Set after remove(): {'Python', 'Swift'}

Here, we have used the discard() method to remove 'Java' from the languages set.

Built-in Functions with Set

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used with sets to perform different tasks.



Returns True if all elements of the set are true (or if the set is empty).

# all values true
l = [1, 3, 4, 5]
# all values false
l = [0, False]

# one false value
l = [1, 3, 4, 0]
# one true value
l = [0, False, 5]

# empty iterable
l = []


Returns True if any element of the set is true. If the set is empty, returns False.

# True since 1,3 and 4 (at least one) is true
l = [1, 3, 4, 0]
# False since both are False
l = [0, False]
# True since 5 is true
l = [0, False, 5]
# False since iterable is empty
l = []


Returns an enumerate object. It contains the index and value for all the items of the set as a pair.

grocery = ['bread', 'milk', 'butter']
enumerateGrocery = enumerate(grocery)

# converting to list

# changing the default 
Grocery = enumerate(grocery, 10)


Returns the length (the number of items) in the

testList = []
print(testList, 'length is', len(testList))

testList = [1, 2, 3]
print(testList, 'length is', len(testList))

testTuple = (1, 2, 3)
print(testTuple, 'length is', len(testTuple))

testRange = range(1, 10)
print('Length of', testRange, 'is', len(testRange))


Returns the largest item in the set.

number = [3, 2, 8, 5, 10, 6]
largest_number = max(number);
print("The largest number is:", largest_number)


Returns the smallest item in the set.

number = [3, 2, 8, 5, 10, 6]
smallest_number = min(number);
print("The smallest number is:", smallest_number)


Returns a new sorted list from elements in the set(does not sort the set itself).

# vowels list
py_list = ['e', 'a', 'u', 'o', 'i']
# string
py_string = 'Python'
# vowels tuple
py_tuple = ('e', 'a', 'u', 'o', 'i')


Returns the sum of all elements in the set.

numbers = [2.5, 3, 4, -5]

# start parameter is not provided
numbers_sum = sum(numbers)

# start = 10numbers_sum = sum(numbers, 10)

Iterate Over a Set in Python

ruits = {"Apple", "Peach", "Mango"}

# for loop to access each fruits
for fruit in fruits: 



Python Set Operations

Python Set provides different built-in methods to perform mathematical set operations like union, intersection, subtraction, and symmetric difference.

Union of Two Sets

The union of two sets A and B include all the elements of set A and B.

We use the | operator or the union() method to perform the set union operation. For example,

# first set
A = {1, 3, 5}

# second set
B = {0, 2, 4}

# perform union operation using |
print('Union using |:', A | B)

# perform union operation using union()
print('Union using union():', A.union(B)) 


Union using |: {0, 1, 2, 3, 4, 5}
Union using union(): {0, 1, 2, 3, 4, 5}

Note: A|B and union() is equivalent to A ⋃ B set operation.

Set Intersection

The intersection of two sets A and B include the common elements between set A and B.

In Python, we use the & operator or the intersection() method to perform the set intersection operation. For example,

# first set
A = {1, 3, 5}

# second set
B = {1, 2, 3}

# perform intersection operation using &
print('Intersection using &:', A & B)

# perform intersection operation using intersection()
print('Intersection using intersection():', A.intersection(B)) 


Intersection using &: {1, 3}
Intersection using intersection(): {1, 3}

Note: A&B and intersection() is equivalent to A ⋂ B set operation.

Difference between Two Sets

The difference between two sets A and B include elements of set A that are not present on set B.

We use the - operator or the difference() method to perform the difference between two sets. For example,

# first set
A = {2, 3, 5}

# second set
B = {1, 2, 6}

# perform difference operation using &
print('Difference using &:', A - B)

# perform difference operation using difference()
print('Difference using difference():', A.difference(B)) 


Difference using &: {3, 5}
Difference using difference(): {3, 5}

Note: A - B and A.difference(B) is equivalent to A - B set operation.

Set Symmetric Difference

The symmetric difference between two sets A and B includes all elements of A and B without the common elements.

In Python, we use the ^ operator or the symmetric_difference() method to perform symmetric difference between two sets. For example,

# first set
A = {2, 3, 5}

# second set
B = {1, 2, 6}

# perform difference operation using &
print('using ^:', A ^ B)

# using symmetric_difference()
print('using symmetric_difference():', 


using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}

Check if two sets are equal

We can use the == operator to check whether two sets are equal or not. For example,

# first set
A = {1, 3, 5}

# second set
B = {3, 5, 1}

# perform difference operation using &
if A == B:
    print('Set A and Set B are equal')
    print('Set A and Set B are not equal')


Set A and Set B are equal

In the above example, A and B have the same elements, so the condition

if A == B

evaluates to True. Hence, the statement print('Set A and Set B are equal') inside the if is executed.

Related Posts

See All

Mastering Lists in Python

Introduction Lists are one of the most fundamental and versatile data structures in Python. They allow you to store and manipulate collections of items, making them an essential tool for any Python pr

Python Anonymous Function

In Python, an anonymous function is a function that is defined without a name. It is also known as a lambda function because it is created using the `lambda` keyword. Anonymous functions are typically


bottom of page