Python set Functions

This article demonstrates the available built-in Python set functions or functions, accompanied by an example of each function. Apart from the set-specific functions, we also demonstrate how to utilize common iterable functions within set elements.

As we already know, a set is a collection of unique elements with no particular order. Since sets are mutable, we can perform various operations to change the existing elements. The Python programming language provides various built-in methods for performing all kinds of operations on set elements.

TIP: Please refer to the Python set article to understand the creation and other details about sets in Python.

List of Python Set Methods

The following table lists the built-in Python set methods or functions that we can use on set elements to perform various operations.

FunctionsDescription
addIt adds an element to a set.
clearIt removes all existing elements from a set.
copyReturns a copy of an original set.
discardIt removes a specific item.
lenIt finds the length of a set.
popRemoves an element from a set and returns it as output.
maxIt returns the maximum value in a set.
minIt returns the minimum value in a set.
removeRemoves a specified element from a set.
sortedIt sorts the given set in ascending or descending order.
update()It updates a set with items from other sets. Merging of two sets.

Please follow the next sections to see an example of each set function. I suggest using the hyperlinks to see a more detailed explanation of each built-in set method in Python programming language.

Python set methods to add elements

There are three ways to add an element to an existing set. The add() method helps add a single item at once. On the other hand, update() will update the existing set elements or add multiple elements. Whereas the copy() function performs a shallow copy of all items to a new set.

Set add()

The Python set add() function adds an element to an existing set. If the element already exists, it won’t be added because sets won’t allow duplicates.

st = {1, 2, 3, 4}

st.add(5)
print(st)
{1, 2, 3, 4, 5}

Python Set methods – copy()

The set copy() method does not accept any argument and performs a shallow copy of an existing set into a new one. It helps to duplicate and perform different kinds of set operations without disturbing the original ones.

In the following program, the copy() method copies the ‘st’ set to new_St. Next, we added a new value to the original set ‘st’. The value 5 does not reflect in the new_st because new_st is independent.

st = {1, 2, 3, 4}
new_st = st.copy()
print(new_st)

st.add(5)
print(st)
print(new_st)
{1, 2, 3, 4}
{1, 2, 3, 4, 5}
{1, 2, 3, 4}

Python set functions – update()

Unlike the add() function, we can use the set update() method to add multiple values to an existing list. It accepts a list of items, or we can merge two lists.

In the following example, we declared two sets. Next, use the set update() function to merge those two sets.

s = {1, 2, 3}
n = {4, 5, 6}

s.update(n)
print(s)
{1, 2, 3, 4, 5, 6}

This example uses a list of items inside an update() function, and it adds those lists to the set.

s = {1, 2, 3}

s.update([9, 10])
print(s)
{1, 2, 3, 9, 10}

TIP: The add() function allows adding one set element at a time. For multiple items, we must use the update() function.

Python set methods to remove items

There are three popular methods to remove an item from a set, and each follows its own technique to perform this operation. They are remove(), discard(), and pop() functions. Apart from those three, there is the clear() method to remove all items from a set in one go.

remove()

The Python set remove() function accepts an argument and removes the given item from the set. If it does not find the given set element, it returns a KeyError.

st = {1, 2, 3, 4}

st.remove(1)
print(st)
{2, 3, 4}

If you write the line below, it will throw KeyError: 9 because there is no 9 inside the given set.

st.remove(9)

Python set methods – discard()

The set discard() method is similar to the remove() function in removing an item from a set. Unlike remove(), the discard() function won’t raise an error if the element does not exist.

st = {1, 2, 3, 4}
st.discard(3)
print(st)
{1, 2, 4}

If we use the discard() function on a non-existing set item (7), it does nothing (no error) and prints the same set.

st.discard(7)
print(st)

pop()

The set pop() function removes a random element from a given set. Since a set is an ordered list of items, the pop() function result may differ in each environment.

st = {1, 2, 3, 4}

print(st.pop())
print(st)

Result

1

{2, 3, 4}

Python Set functions – clear()

The set clear() method does not take any arguments and removes all the existing elements in a set. It does not return any value. However, if you print the set after calling the clear() function, it returns an empty set.

TIP: Use clear() to delete all items and keep the set.

st = {1,2, 3, 4}
st.clear()
print(st)

Result

set()

In the following series of examples, we are using only two sets to demonstrate the working functionality. However, we can use more than one set as an argument. Please use a comma to separate multiple sets. For example, s.union(set1, set2, set3).

Python set methods to perform set operations

The following table shows the set operations to perform set operations, including finding the union, intersection, and difference.

FunctionsDescription
unionReturns a set that contains the union of all sets.
intersection()Finds the intersection between two or more sets and returns a set.
intersection_update()It updates the existing set with the result of the intersection().
issubset()It returns True if the first set is a subset of the second one.
issuperset()It returns True if the first set is a superset of the second one.
isdisjoint()It returns True if there are no common elements in the given sets.
difference()Finds the difference between two or more sets and returns a new set.
difference_update()It updates the existing set with the result of the difference().
symmetric_difference()It returns the unique or distinct elements that are not common in the given sets.
symmetric_difference_update()It updates the existing set with the result of symmetric_difference().
frozenset()It returns an immutable frozen set object. Good for read-only sets.

Set union()

The union() function is one of the Python set methods that returns a new set containing all the elements from two or more sets. Remember, it creates a new set and does not modify the original sets.

In the program below, we declared two sets and then used the union() function on both sets. Here, the final set contains only one 3 because sets won’t allow duplicates.

s = {1, 2, 3}
t = {3, 4, 5}

u = s.union(t)
print(u)
{1, 2, 3, 4, 5}

Set intersection()

The intersection() function is one of the Python set methods that returns a new set containing common elements from two or more sets. Remember, the intersection() creates a new set and does not modify the original sets.

In the program below, the final set contains only {2, 3} because those are the two values that are common in s and t.

s = {1, 2, 3}
t = {3, 9, 5, 2}

u = s.intersection(t)
print(u)
{2, 3}

Python set functions – intersection_update()

The Python intersection_update() method finds the intersection of itself against the given sets and updates the existing set with the intersection result.

In the program below, there are two elements in both sets, namely 1 and 4. So, the intersection_update() function updates ‘s’ set with these values.

s = {1, 2, 3, 4}
t = {1, 9, 4, 5}

s.intersection_update(t)
print(s)
{1, 4}

Set issubset()

The set issubset() function checks whether the given set is a subset of the given argument. If the argument set has all elements of the given set and a few more, then it is a subset, and the issubset() function returns True. Otherwise, it returns False.

top = {'Delhi', 'New York', 'Mumbai', 'Washington'}
India = {'Delhi', 'Mumbai'}

print(India.issubset(top))
True

Python Set methods – issuperset()

The set issuperset() function checks whether the given set is a superset of the given argument. If it is a superset, and the issuperset() function returns True. Otherwise, it returns False.

In the following example, the trending cities have all the top city names and a few extra names. So, naturally, the trend is a superset of the top set.

top = {'New York', 'Mumbai', 'Washington'}
trend = {'London', 'New York', 'Tokyo','Mumbai', 'Washington'}

print(trend.issuperset(top))
True

Set isdisjoint()

The set isdisjoint() function checks whether there are any common values between the given two sets. If there are unique elements, the isdisjoint() function returns a Boolean True. Otherwise, it returns False.

The following example program returns True because all four elements from the given two sets are distinct. There are no common city names between s1 and s2. If we add NewYork to s2, the isdisjoint() function will return False.

s1 = {'Delhi', 'New York'}
s2 = {'Mumbai', 'Washington'}

print(s1.isdisjoint(s2))
True

Python set methods to find the difference

The following four methods, difference(), difference_update(), symmetric_difference(), and symmetric_difference_update(), help find the difference between two or more sets.

Set difference()

The set difference() function finds the difference between two or more given sets and returns a new set containing the distinct elements from them.

In simple words, elements that exist in the first set and are not present in the second set are the difference() result. Remember, the difference() creates a new set and does not modify the original sets.

In the program below, the final set contains only {1, 2} because the two values are not present in t.

s = {1, 2, 3}
t = {3, 4, 5}

u = s.difference(t)
print(u)
{1, 2}

Python Set methods – difference_update()

The set difference_update() function performs the same operation as the difference() function, but it updates the existing set. In simple words, the difference_update() function updates the existing set with elements that exist in the first set and are not present in the second set.

In the program below, the s set will update with {1, 2} because the two values are not present in t.

s = {1, 2, 3}
t = {3, 4, 5}

s.difference_update(t)
print(s)
print(t)
{1, 2}

{3, 4, 5}

Python Set methods – symmetric_difference()

The set symmetric_difference() function compares the two sets to find the unique elements, and returns a new set containing the distinct elements. Remember, the symmetric_difference() function creates a new set and does not modify the original sets.

In the program below, the final set contains only {1, 2, 4, 5}. There are three elements in each set. Among them, 3 is the common element between the two sets (repeated in s and t). So, 1, 2, 4, and 5 are the unique or distinct elements, and the symmetric_difference() function returns unique items.

s = {1, 2, 3}
t = {3, 4, 5}

u = s.symmetric_difference(t)
print(u)
{1, 2, 4, 5}

Python Set methods – symmetric_difference_update()

The set symmetric_difference_update() function performs the same operation as the symmetric_difference(). However, instead of creating a new set, it updates the existing set.

The symmetric_difference_update() function compares the two sets to find the unique elements and updates the existing set with distinct elements.

In the program below, the s set updates with {1, 2, 5}. In both sets, 3 and 4 are common elements. So, 1, 2, and 5 are the unique or distinct elements, and the symmetric_difference_update() function updates the existing set with unique items.

s = {1, 2, 3, 4}
t = {3, 4, 5}

s.symmetric_difference_update(t)
print(s)
print(t)
{1, 2, 5}

{3, 4, 5}

Python set methods to perform aggregations

The following functions are common for all iterables. This section uses len(), min(), max(), sorted(), and sum() functions on set elements to perform aggregations.

len() – Finding the length of a set

The set len() function finds and returns the length or total number of elements in a set.

Syntax

len(set_name)

The following query returns 5 because there are five countries in the declared set.

st = {'USA', 'UK', 'INDIA', 'CHINA', 'EUROPE'}

print(len(st))
5

Python Set methods – min()

The set min() function returns the least or minimum value in a given set. If it is a string, it follows alphabetical order (A – Z). If it is numbers, it return minimum number.

Syntax

min(set_name)

The following program returns CHINA and 9 because C is the least starting alphabet in those 5 elements. Next, 5 is the minimum number among 20, 34, 9, 18, and 70.

s = {'USA', 'UK', 'INDIA', 'CHINA', 'EUROPE'}
print(min(s))

n = {20, 34, 9, 18, 70}
print(min(n))

Result

CHINA

9

Python Set methods – max()

The set max() function returns the highest or maximum value in a given set. If it is a string, it follows (Z- A) alphabetical order. If it is numbers, it return maximum number.

Syntax

max(set_name)

The following program returns USA and 66 because U followed by S is the highest starting alphabet among them. Next, 66 is the maximum number among 20, 34, 66, 9, and 18.

n = {20, 34, 66, 9, 18}
print(max(n))

s = {'UK', 'INDIA', 'USA', 'CHINA', 'EUROPE'}
print(max(s))

Result

66

USA

Python Set methods – sorted()

The set sorted() function sorts the given set elements in ascending or descending order. By default, it sorts in ascending. However, if you pass a reverse argument with a True value, it sorts in descending order.

Syntax

sorted(set_name, reverse = True|False)

The first statement sorts the set elements in ascending order. On the other hand, the second statement sorts the set of items in descending order.

n = {20, 34, 9, 18}
print(sorted(n))
print(sorted(n, reverse=True))

Result

[9, 18, 20, 34]

[34, 20, 18, 9]

Python Set methods – sum()

The set sum() function calculates the sum of the total items in a set.

Syntax

sum(set_name)

The following query returns 147 because the result of the sum of total set items is 20 + 34 + 66 + 9 + 18 = 147.

n = {20, 34, 66, 9, 18}
print(sum(n))
147