What Is the Set Data Structure in Python?


Heather Bennett

The set data structure is a powerful tool in Python that allows you to store a collection of unique elements. In this tutorial, we will explore what sets are, how to create them, and the various operations you can perform on them.

Creating Sets

To create a set in Python, you can use curly braces {} or the built-in set() function. Let’s take a look at some examples:

# Using curly braces
my_set = {1, 2, 3}

# Using set() function
my_set = set([4, 5, 6])

You can see that each element in a set is unique. If you try to add a duplicate element, it will be automatically removed.

Adding and Removing Elements

To add elements to a set, you can use the add() method. Let’s add an element to our existing set:


If we print the updated set, we will see that the element 7 has been added:

# Output: {4, 5, 6, 7}

To remove elements from a set, you have several options. The remove() method removes a specific element:

# Output: {4, 5, 7}

If you’re unsure whether an element exists in the set or not, you can use the discard() method:

# Output: {4, 5, 7}

If you want to remove the last element in the set, you can use the pop() method. However, since sets are unordered collections, the last element is arbitrary:


Set Operations

Sets in Python support various mathematical operations such as union, intersection, and difference. Let’s take a look at each of them:

  • Union: The union of two sets contains all the unique elements from both sets. You can use the union() method or the “|” operator.
  • Intersection: The intersection of two sets contains only the common elements between them.

    You can use the intersection() method or the “&” operator.

  • Difference: The difference between two sets contains all the elements in one set that are not present in the other set. You can use the difference() method or the “-” operator.

set1 = {1, 2, 3}
set2 = {3, 4}

# Union
union_set = set1.union(set2)
# Output: {1, 2, 3, 4}

# Intersection
intersection_set = set1.intersection(set2)
# Output: {3}

# Difference
difference_set = set1.difference(set2)
# Output: {1, 2}


Sets are a useful data structure in Python when you need to store a collection of unique elements. They provide efficient membership testing and support various mathematical operations. By using sets, you can eliminate duplicates and perform set-related operations easily.

In this tutorial, we covered the basics of sets in Python, including creating sets, adding and removing elements, and performing set operations. Now you have a good understanding of sets and can start incorporating them into your Python programs.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy