How to use Python Sets

In this tutorial, I go through the basics of Python sets and how you can use them.

How to use Python Sets

Sets in Python are used to store multiple items within a single variable. Each item contains a value that can be a string, Boolean, integer, and more. An item within a set is identified by its value and is not indexed.

A set is best for when you require an unordered collection of unique elements. They are ideal for checking whether an item exists within it.

The syntax of a set consists of curly brackets and comma-separated items within the brackets. For example, {"Apple", "Orange"} is a two item set.

It is important to note that a set is unordered, and you cannot update existing items within the set. However, you can still add and remove items from within a set. Duplicate items are not supported. If a set does not sound ideal for your current requirements, you may want to look at dictionaries, lists, or tuples.

This guide is written under the assumption that you are using Python 3 or later.

Table of Contents

Creating a Set

You will need to know a few things about creating a set in Python and why you may want to use one.

A set in Python is defined by a range of items enclosed by curly brackets. Each item contains a single value with a comma indicating the end of an item and the start of a new item. An item within a set looks like the following "apple",.

You cannot update items within a set after it has been created. However, a set is not completely immutable, and you can still add new items and remove existing ones.

A set is unordered, so there is no defined order for the items. Therefore, you cannot use an index or key to access the items, and they may appear in a different order every time you access the set.

You are unable to have duplicate items within a set. If there are duplicates, they will simply be ignored by Python.

Items within a set can be of any data type, such as strings, integers, Boolean, and more will be supported. However, remember duplicate items are not supported.

Set Example

The example below shows how you can create a set in Python. We use strings and integers as the items within our set.

We output our set items and verify it is a set by outputting the type.

exampleSet = {"Apple", 1 , "Banana", 0, "Orange"}

print(exampleSet)

print(type(exampleSet))

You can see all the items within our set in the output below. You will notice that they are in a different order from how we initialized them. The ordering will change every time you run the code. The last line is the data type, which is “set”.

python set.py
{0, 1, 'Apple', 'Orange', 'Banana'}
<class 'set'>

Accessing Set Items

You cannot access set items using a key or index as they do not use keys, and they are unordered. Instead, you will need to use a for loop and the in keyword to find the item you require.

In the example below, we print out each of our items within the set. You could use an if statement to output a specific item to control when print() fires.

fruitSet = {"Apple", "Orange", "Pear"}

for x in fruitSet:
    print(x)

As you can see below, our set items were printed into the terminal. If you rerun the script, the order of the items will be different.

python set.py
Orange
Apple
Pear

Checking for a Set Item

You can use the in keyword with an if conditional statement to check whether a set item exists.

In the example below, we check to see if our string “Apple” exists within the set. Then, we print a statement depending on the outcome of the check.

fruitSet = {"Apple", "Orange", "Pear"}

if "Apple" in fruitSet:
    print("Apple is in the set.")
else:
    print("Apple is not in the set.")

The output below shows that Python found our string within the set and printed the correct line.

python set.py
Apple is in the set.

Adding Set Items

You can use a few different techniques to add new items to a set. In this section, we will go through how to use the add() or update() method to add new items.

It is important to remember that sets do not support duplicate items, so nothing will happen if you try adding an existing item.

Using add()

You can use the add() method to add a new item into a set. However, if you want to add multiple items, you will need to use the update() method.

In the example below, we use the add method to add a string into our set.

fruitSet = {"Apple", "Orange", "Pear"}

fruitSet.add("Banana")

print(fruitSet)

The output below shows that the add() method successfully added our new item to the set.

python set.py
{'Apple', 'Pear', 'Banana', 'Orange'}

Using update()

The update() method is perfect for adding multiple items into a set.

In this example, we will add a set into our main set, but you can use any iterable object such as tuples, dictionaries, and lists.

fruitSet = {"Apple", "Orange", "Pear"}

fruitSet.update({"Banana", "Mango", "Watermelon"})

print(fruitSet)

Our output below shows that our new set has been added to our main set.

python set.py
{'Orange', 'Apple', 'Watermelon', 'Pear', 'Banana', 'Mango'}

Deleting Set Items

There are quite a few different techniques to remove items within a set. We will go through using remove(), discard(), pop(), and clear(). Each choice has its uses, which we will talk about in each section.

Using remove()

You can use the remove() method to remove an item from a set. You will need to use the item’s value as an argument if you wish to remove it. If you attempt to remove an item that does not exist, Python will throw an error.

fruitSet = {"Apple", "Orange", "Pear"}

fruitSet.remove("Orange")

print(fruitSet)

The output below shows that the item containing “Orange” was removed from the set.

python set.py
{'Apple', 'Pear'}

Using discard()

The discard() method is essentially the same as remove(). It accepts a single parameter: the value of the item you wish to discard. Attempting to remove an item that does not exist will result in an error.

fruitSet = {"Apple", "Orange", "Pear"}

fruitSet.discard("Orange")

print(fruitSet)

Below you can see that we successfully removed the item containing “Orange” from the set.

python set.py
{'Pear', 'Apple'}

Using pop()

You can use the pop() method to remove the last item in the set. However, since sets are unordered, the last item will be random, so you will not know which item will be removed.

The value of the item removed will be returned from the pop() method.

Our example below uses pop to remove an item and store it in a variable. We output both the set and the variable containing the removed item.

fruitSet = {"Apple", "Orange", "Pear"}

popValue = fruitSet.pop()

print(fruitSet)

print("Removed " + popValue)

In the output below, you can see that we removed the last element and printed its value.

python set.py
{'Pear', 'Apple'}
Removed Orange

Using clear()

Use the clear() method if you wish to remove all items without removing the set itself. The example below demonstrates how to use clear() on a set.

fruitSet = {"Apple", "Orange", "Pear"}

fruitSet.clear()

print(fruitSet)

Since our set is empty, just “set” is outputted when we run the Python script.

python set.py
set()

Deleting a Set

You can use the del keyword to delete a set entirely. If you try to access the set after it has been deleted, Python will throw an error.

fruitSet = {"Apple", "Orange", "Pear"}

print(fruitSet)

del fruitSet

print(fruitSet)

The output below shows the set before and after it has been deleted. When we tried to print the deleted set, Python threw an error.

python set.py
{'Pear', 'Orange', 'Apple'}
Traceback (most recent call last):
  File "G:\Python\set.py", line 7, in <module>
    print(fruitSet)
NameError: name 'fruitSet' is not defined

Set Operators

You can use operators or methods to perform a range of different actions on a set. In this section, we will touch on some of the different ways you can interact with a set.

Set Union

Using the union operator or method will return a set that contains the original set items and the second set items. You can use union on multiple sets.

The image below demonstrates how union works on set X and set Y.

Python set Union

You can use the union() method or the | operator to perform a union on two or more sets. In the example below, we use both the method and operator to combine the two sets.

xSet = {"Apple", "Orange", "Pear"}

ySet = {"Potato", "Carrot", "Orange"}

print(xSet | ySet)

print(xSet.union(ySet))

As you can see in the output below, union combined our two sets into a single set. It is important to note that since sets do not support duplicates, orange remains as a single entry.

python set.py
{'Carrot', 'Potato', 'Pear', 'Orange', 'Apple'}
{'Carrot', 'Potato', 'Pear', 'Orange', 'Apple'}

Set Intersection

Using the intersection operator or method will return a set that only contains items that exist in both sets. You can use intersection on multiple sets.

The image below demonstrates how intersection works on two sets. The red represents the matching items.

Python set Intersection

You can use the intersection() method or the & operator to perform an intersection on multiple sets. For example, the code below uses both techniques to demonstrate how it works on two sets.

xSet = {"Apple", "Orange", "Pear"}

ySet = {"Potato", "Carrot", "Orange"}

print(xSet & ySet)

print(xSet.intersection(ySet))

Our output only contains orange as it is the only item in both sets.

python set.py
{'Orange'}
{'Orange'}

Set Difference

Using the difference operator or method, Python will return a set containing items that only exist in the original set. If they exist in both sets or only in the second set, the difference method will remove them.

Our diagram below visualizes how difference works on two sets. Items that exist in both or just y will be removed.

Python set Difference

To perform difference on two sets, you can use the difference() method or the - operator. The example code will run both techniques on our two sets to demonstrate how difference works.

xSet = {"Apple", "Orange", "Pear"}

ySet = {"Potato", "Carrot", "Orange"}

print(xSet - ySet)

print(xSet.difference(ySet))

Our output contains two items as Pear and Apple are the only two items that are not in Y.

python set.py
{'Pear', 'Apple'}
{'Pear', 'Apple'}

Set Symmetric Difference

Using the symmetric operator or method will return items from both sets, but only if they don’t already exist in both.

The diagram below demonstrates how symmetric difference will work on two sets. Any items that are in both sets will be removed.

Python set Symmetric Difference

To perform symmetric difference on two sets, you will need to use the symmetric_difference() method or the ^ operator. The code below demonstrates how to use them on two different sets.

xSet = {"Apple", "Orange", "Pear"}

ySet = {"Potato", "Carrot", "Orange"}

print(xSet ^ ySet)

print(xSet.symmetric_difference(ySet))

The output below contains items that exist in either setX or setY. If an item existed in both sets, it was removed.

python set.py
{'Carrot', 'Pear', 'Potato', 'Apple'}
{'Carrot', 'Pear', 'Potato', 'Apple'}

Python Set Built-in Methods

Below is a range of different methods that you can use on sets. We have covered some of these methods in this tutorial, but not all of them. I hope this list helps you work out the best method for what you wish to do.

set.add(item)Will add a new item to a set.
set.clear()Clears all items from a set.
setX.difference(setY)Returns a set that contains items that only exist in the original set. It removes items that are in both sets.
setX.difference_update(setY)Removes items from setX that exist in both sets.
set.discard(item)Will remove the specified item from a set.
setX.intersection(setY)Returns a set that contains items that only exist in both sets. You can add multiple sets as a parameter.
setX.intersection_update(setY)Removes the items from setX that do not exist in both sets. You can specify multiple sets as a parameter.
setX.isdisjoint(setY)Will return true if some items exist in both sets. Otherwise, it will return false.
setX.issubset(setY)Returns true if all items in setX exist in setY. Otherwise, it will return false.
setX.issuperset(setY)Will return true if all items in setY exist in setX. Otherwise, it will return false.
set.pop()Removes the last item within a set.
set.remove(item)Will remove the specified item from a set.
setX.symmetric_difference(setY)Returns a set that contains items from both sets except for items that exist in both sets.
setX.symmetric_difference_update(setY)Removes items that exist in both sets and adds any remaining items to the original set.
setX.union(setZ, setY...)Returns a set containing the specified sets and the original set.
set.update(object)Updates the set with a set or other iterable object.

Conclusion

I hope this guide has taught you the basics of using sets in Python. We covered topics such as creating, accessing, and deleting set items. We also touched on some of the methods and operators you can use.

There is always more to learn when it comes to programming in Python. I recommend checking out some other data collection types such as lists, dictionaries, and tuples. Understanding the different data types will help write better code.

Please let us know if there are any improvements we can make to this tutorial by leaving a comment at the bottom of this page.

Leave a Reply

Your email address will not be published. Required fields are marked *