---
title: "How To Use Sets in Python"
description: "Learn how to use sets in Python to create, add, and manage data collections within code. Leverage data flexibility and learn to use sets in Python today!"
canonical: "https://adamtheautomator.com/sets-in-python/"
---

# How To Use Sets in Python

> Learn how to use sets in Python to create, add, and manage data collections within code. Leverage data flexibility and learn to use sets in Python today!

Source: https://adamtheautomator.com/sets-in-python/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![How To Use Sets in Python](https://adamtheautomator.com/wp-content/uploads/2021/11/How-To-Use-Sets-in-Python.jpg)

# How To Use Sets in Python

[![](https://secure.gravatar.com/avatar/c23ad7f54ebee518a440f0f0771fca0529c90f59ff25f5dbcb3a899a9902ac8a?s=192&d=mm&r=g)Dubson Brittin](https://adamtheautomator.com/author/dubson-britton/)10 November 20219 min. read

Categories: [DevOps](/category/devops/)

Tags:[Linux](/tag/linux/)[Python](/tag/python/)[Windows](/tag/windows/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Creating Your First Sets in Python](#creating-your-first-sets-in-python)
*   [Understanding Sets Defining Properties](#understanding-sets-defining-properties)
*   [Adding Elements to a Python Set](#adding-elements-to-a-python-set)
*   [Removing Elements from a Python Set](#removing-elements-from-a-python-set)
*   [Learning the Clear Method](#learning-the-clear-method)
*   [Using the Remove Method](#using-the-remove-method)
*   [Removing Elements With the Discard Method](#removing-elements-with-the-discard-method)
*   [Taking Elements Out via the Pop Method](#taking-elements-out-via-the-pop-method)
*   [Conclusion](#conclusion)

Learn to use sets in Python as an entry point for Python learners and Python programmers to learn and/or code on more advanced concepts like [Lambda](https://aws.amazon.com/lambda/) functions, [Map Reduce](https://www.learnpython.org/en/Map%2C_Filter%2C_Reduce), Java Collections API, and Python collections interface.

This tutorial will look into several everyday use cases of the set data structure in the Python programming language with examples to help you better understand the concepts.

Read on to get started!

## Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:

*   Python v3 or later environment installed.
*   A code editor to run Python code such as [VS Code](https://code.visualstudio.com/download).

Related:[How Do You Install Python 3.6?](https://adamtheautomator.com/install-python-36/)

## Creating Your First Sets in Python

In Python, two data structures are [lists](https://www.w3schools.com/python/python_lists.asp), which are ordered collections of mutable data, and [dictionaries](https://www.w3schools.com/python/python_dictionaries.asp) that store data in key-value pairs. [Mutable](https://towardsdatascience.com/https-towardsdatascience-com-python-basics-mutable-vs-immutable-objects-829a0cb1530a) means that the data can be changed after its creation. Sets share characteristics of both lists and dictionaries. Like lists, sets are mutable collections of single elements.

Unlike lists, sets have no index because they’re not a sequence, making sets more akin to dictionaries, which are also unordered collections. Python highly optimizes both sets and dictionaries for look-up operations, increasing speed.

You can look up a key to get a value in a dictionary, like finding somebody’s name and then getting their phone number when you look in an address book. But sets do not contain key-value pairs. Instead, you look up an element within sets to check if it does or does not exist in the set. This concept is called [membership testing](https://www.geeksforgeeks.org/python-membership-identity-operators-not-not).

To learn, it’s time to create a set! You create a set by adding elements to a set. Let’s get your hands dirty!

1\. Start an [interactive Python session](https://en.wikibooks.org/wiki/Python_Programming/Interactive_mode) in the terminal.

2\. Once your Python session is ready, create a set by calling the [`set()`](https://www.geeksforgeeks.org/python-set-method/) method and pass in any type of data you want to add. Copy and paste the code below into your Python session and press **Enter** to create your first set. You are declaring the `my_firs_set` [variable](https://www.w3schools.com/python/python_variables.asp), with the set [literal](https://www.geeksforgeeks.org/literals-in-python/): curly braces. The `ATA, Hello World` string is the first and only element.

```python
my_first_set = {'ATA, Hello World'}
```

3\. Run the command below to call your first set to check that it creates the set.

```python
my_first_set
```

You will get the string, `ATA, Hello World` in return, as shown below.

![Creating and calling a set](https://adamtheautomator.com/wp-content/uploads/2021/11/image-160.png)

Creating and calling a set

4\. You can double-check that `my_first_set` is a set by using the [`type()`](https://www.geeksforgeeks.org/python-type-function/) function to get the data type of the `my_first_set`. Run the code below to get the data type.

```javascript
type(my_first_set)
```

You will get the output shown below. The output confirms `my_first_set` is a set.

![Checking my\_first\_set type](https://adamtheautomator.com/wp-content/uploads/2021/11/image-161.png)

Checking `my_first_set` type

5\. Since a set is a collection, it has the built-in length function: `len()`. Run the code below to get the length of the set.

```javascript
len(my_first_set)
```

In return, you will get **1,** as shown below, because the set contains only one element. A set containing exactly one element is also known as a singleton set.

![Checking the length of the set](https://adamtheautomator.com/wp-content/uploads/2021/11/image-162.png)

Checking the length of the set

## Understanding Sets Defining Properties

A set has two defining properties, both of which you will see next. Nobody likes spoilers, read on to start coding and learn about these properties.

[Create](https://www.geeksforgeeks.org/create-an-empty-file-using-python/) a new file named _set\_comparison.py_, and copy-paste the code below into it.

```python
# You will make a couple of sets. The first set is {1, 2, 3}, 
# the second set has the same numbers in a different order {3, 2, 1}.
# You'll use a double equal sign == to compare the sets. # And you'll use a print statement to print out the result of this comparison.
print({1, 2, 3} == {3, 2, 1})
```

Run the command below in your IDE to run the _set\_comparison.py_ script and print out the comparison output.

```javascript
python set_comparison.py
```

You will get **true** as output as shown below: Python evaluated these two sets and considered both of them equal. They are of the same length, and they contain the exact same elements as each other.

When an element is in a set, it is guaranteed to be unique from other elements. In concrete words, a set is a mathematical object that keeps track of all the distinct values in a given collection or string.

> 1️⃣ _Python sets are not sequences: the order of the elements in the set does not matter. Sets are unordered._

![Comparing sets and noticing that order of elements does not matter](https://adamtheautomator.com/wp-content/uploads/2021/11/image-163.png)

Comparing sets and noticing that order of elements does not matter

Next you will learn how sets handle duplicate values. [Create](https://www.geeksforgeeks.org/create-an-empty-file-using-python/) a new file named _set\_integer\_number.py_, copy and paste the line below. Each member of this set literal will be an integer, separated by commas, and some of these integers will repeat in no particular order.

```python

print({1, 2, 3, 2, 3, 4, 3, 4, 4, 4})
```

Run the command below to print out members of the set.

```javascript
python set_integer_number.py
```

You will get the output like the one below, where you can see that `set_integer_number` contains only the unique values **1**, **2**, **3**, and **4**. Even though you’ve repeated almost all of them. When Python evaluates and constructs, and prints out the actual set, you only have four members in the set.

When an element is in a set, it is guaranteed to be unique from other elements. In concrete words, a set is a mathematical object that keeps track of all the distinct values in a given collection or string.

> 2️⃣ _Python sets do not contain duplicate data: there are no duplicate values. Members are uniquely different from one another._

![The code attempts to add duplicate values to a set, but sets contain no duplicate values.](https://adamtheautomator.com/wp-content/uploads/2021/11/image-164.png)

The code attempts to add duplicate values to a set, but sets contain no duplicate values.

You can double-check if duplicate values are stored by printing out the length of this set by using the `len()` method. Remove the previous content from the _set\_integer\_number.py_ file and copy and paste the line below into the _set\_integer\_number.py_ file.

```python
print(len({1, 2, 3, 2, 3, 4, 3, 4, 4, 4}))
```

Run the command below to print out the length of the set.

```python
python set_integer_number.py
```

You will get the number **4** in the output as shown below, meaning that there are only four members in the set.

![You will get the number 4 in the output as shown](https://adamtheautomator.com/wp-content/uploads/2021/11/image-165.png)

You will get the number 4 in the output as shown

Contrast these properties with a real-life example of a set. A set of fruits: apples, bananas, oranges, lemons, and limes. The order of the fruits does not matter. If you change the order of the list, nothing will be different. You still have the same list of fruits. Apples are no more important than bananas or lemons.

All the fruits are unique and are distinctly different from each other. If someone asks you to name five fruits, you wouldn’t say bananas five times: once is enough. Since bananas are already in the set, adding them again shouldn’t change the set.

## Adding Elements to a Python Set

In the previous section, you’ve learned how to create a new Python set. In this section, you’ll learn how to manipulate Python sets. First up is adding elements to a set.

> _Python sets are mutable, meaning that the data inside a set can be changed after the set creation._

There are two methods for adding elements to a set. The [`add()`](https://www.programiz.com/python-programming/methods/set/add) method adds one element, while the [`update()`](https://www.w3schools.com/python/ref_dictionary_update.asp) method adds more than one element.

Create a new file named _set\_vowels.py_, copy and paste the code below to the file.

```python
# You'll declare a new variable vowels and assign it as an empty set.
vowels = set()
#Use the add() method to add one element to the set. 
# Let's add A, which was the first vowel.
vowels.add('A')
#Print the new set with the added element.
print(vowels)
```

Run the code below to check that you are adding elements to the set.

```python
python set_vowels.py
```

You will get an output like the one below. Notice that it prints ‘**A**‘ when you print _set\_vowels_ content, meaning that ‘**A’** is a member of `set_vowels`_._

![Printing out the set](https://adamtheautomator.com/wp-content/uploads/2021/11/image-166.png)

Printing out the set

Now, instead of adding the rest of the vowels one by one, it’s time to add them all together with the update method.

Copy and paste the line below to your _set\_vowels.py_ file. You’ll use an [iterable](https://www.pythontutorial.net/python-basics/python-iterables/) type, which is a string: **U**, **E**, **O**, and **I**. The update method will go through every element one by one, making the string iterable, and add each element to the set.

```python
vowels.update('U, E, O, I')
```

Run the code below to check that the set contains all four newly added vowels.

```python
python set_vowels.py
```

You will get the output shown below. You can see it adds all of the vowels to the set.

![Checking the set](https://adamtheautomator.com/wp-content/uploads/2021/11/image-167.png)

Checking the set

> _The order is non-deterministic for these [string](https://www.w3schools.com/python/python_strings.asp) data types. So if your vowels come out in a different order, that’s fine; it’s working as intended._

## Removing Elements from a Python Set

In the previous section, you’ve learned how to add elements to a set. In this section, you’ll learn how to remove elements from a set.

There are four methods to remove an element from a Python set:

*   [`clear()`](https://www.programiz.com/python-programming/methods/set/clear)
*   [`remove()`](https://www.programiz.com/python-programming/methods/set/remove)
*   [`discard()`](https://www.w3schools.com/python/ref_set_discard.asp)
*   [`pop()`](https://www.w3schools.com/python/ref_set_pop.asp)

Let’s go into each method one by one. The examples will rely on the vowels set from the previous section. You will create a copy instead of the original set to not affect the original set.

The [`copy()`](https://www.geeksforgeeks.org/set-copy-python/) method makes a copy of the set. For example, copy and paste the lines below into your _set\_vowels.py_ file to make a copy for each removing method.

```powershell
clear_method = vowels.copy()
remove_method = vowels.copy()
discard_method = vowels.copy()
clear_method = vowels.copy()
```

### Learning the Clear Method

The first method is the `clear()` method, whose syntax is `set.clear()`. This method does not take any argument.

Copy and paste the lines below into your _set\_vowels.py_ to call out the `clear()` method and print out the `clear_method` set

```python
clear_method.clear()
print(clear_method)
```

Run the code below, and you will get an empty set printed out as shown below. The `clear()` method removed all the elements from the set.

```python
python set_vowels.py
```

![Printing out an empty set](https://adamtheautomator.com/wp-content/uploads/2021/11/image-168.png)

Printing out an empty set

### Using the Remove Method

Now, onto the `remove()` method. This method takes one argument, which is the element you want to remove from the set. The syntax for the `remove()` method is `set.remove(element)`. You will use this method in your code below.

```python
remove_method = vowels.copy()
# Rmove the letter A.
remove_method.remove('A')
print(remove_method)
```

Run the code below to check that the removal of the letter **A** from the `remove_method` set.

```python
python set_vowels.py
```

You will get an output like shown below. You can see that A is no longer part of the set.

![A is no longer part of the set](https://adamtheautomator.com/wp-content/uploads/2021/11/image-169.png)

A is no longer part of the set

If you try to remove an element that doesn’t exist in the set, you’ll get a key error. Let’s invoke the `remove()` method with an element that is not a member of the set, the B letter.

```python
remove_method = vowels.copy()
remove_method.remove('B')
print(remove_method)
```

Re-run _set\_vowels.py,_ and you will get an output showing an error, like the one below.

![Getting an error](https://adamtheautomator.com/wp-content/uploads/2021/11/image-170.png)

Getting an error

### Removing Elements With the Discard Method

The third method is the `discard()` method. This method takes one argument, which is the element you want to remove from a set.

The difference between `remove()` and `discard()` is that if an element does not exist, the discard() method will not raise an error. This method avoids raising a **KeyError,** and you can call `discard()` as many times as desired.

The syntax of the `discard()` method is `set.discard(element)`. Once again, copy and paste the code below. You will discard the **B** letter, which is not a member of the set, and this time Python will not raise an error.

```python
discard_method = vowels.copy()
discard_method.discard('B')
print(discard_method)
```

Run _set\_vowels.py_ again and see what happens.

```python
python set_vowels.py
```

You will get an output like the one shown below. You can see that there is no error.

![Discarding an element that is not part of the set does not raise errors;](https://adamtheautomator.com/wp-content/uploads/2021/11/image-171.png)

Discarding an element that is not part of the set does not raise errors;

### Taking Elements Out via the Pop Method

The last method is the `pop()` method. This method takes no argument, removes a random element from the set, and returns the removed element. The syntax for pop() method is `set.pop()`.

Copy and paste the code below to invoke the `pop()` method and print out the removed element.

```python
pop_method = vowels.copy()
vowel = pop_method.pop()
print(vowel)
print(pop_method)
```

Run _set\_vowels.py,_ and you will get an output like the one shown below. The original vowel set has five vowels in it. Your `pop_method` set has four vowels: the method removes and returns the vowel **O**.

![Removing a random element with pop()](https://adamtheautomator.com/wp-content/uploads/2021/11/image-172.png)

Removing a random element with `pop()`

Since `pop()` removes a random element, you might have gotten a different result. Run the code multiple times, and you will notice the randomness at play.

![Running the script once again to prove pop() randomness](https://adamtheautomator.com/wp-content/uploads/2021/11/image-173.png)

Running the script once again to prove `pop()` randomness

## Conclusion

You should now have a better understanding of Python sets and the methodology needed to create, remove or add elements to sets. As a next step, why not explore [set operations & sets vs. lists](https://www.datacamp.com/community/tutorials/sets-in-python)?

Related:[Python Input: How to Accept User Input to Python Scripts](https://adamtheautomator.com/python-input/)

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fsets-in-python%2F&text=How%20To%20Use%20Sets%20in%20Python)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fsets-in-python%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fsets-in-python%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2021/12/Creating-Statistical-Plots-with-the-Seaborn-Python-Library.jpg)

### [Creating Statistical Plots with the Seaborn Python Library](/seaborn-python/)

Are you still using Excel to generate statistical plots? Perhaps it’s time to ditch it and switch to the Seaborn Python library to create many beautiful plots.

![](https://adamtheautomator.com/wp-content/uploads/2025/11/55418e927e511ae263219c072e27d637c2a967a5036de7020b329582db775c26.png)

### [Automating Docker Container Health Checks with Python and Local Notifications](/docker-health-checks-python/)

Docker's built-in health checks are passive—they tell Docker when a container fails, but do they tell you? In this tutorial, we'll build a lightweight Python monitoring system that runs entirely on your infrastructure with zero external dependencies. You'll learn to detect container failures in real-time, send instant alerts, and maintain a complete audit log of every state change.

![](https://adamtheautomator.com/wp-content/uploads/2023/11/automating-tasks.jpg)

### [Automating Tasks Using Bash Scripts and Cron Jobs with AWS](/automating-tasks/)

Discover how to combine bash scripts with cron jobs and leverage the power of AWS for automating tasks in this ATA Learning tutorial!

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
