20th Nov 2023 8 minutes read Python Set Examples: From Basic to Advanced Use Cases Juliano Luiz Faccioni python sets Learn how to use Python sets and set operations like a pro! Learn what sets are, how to create them, and how to work with them in real-world use cases. In the world of Python data types, Python sets are not as famous as lists, dictionaries, or tuples. Even seasoned Python developers are sometimes unaware of how useful Python sets can be. But worry not: This article will provide you with clear explanations of Python sets, and practical examples on how to use them. We’ll start by learning how to create Python sets, what their defining traits are, and how they compare to lists and other common Python data structures. We’ll then go over the set operations and learn about some common use cases for Python sets. If you rather dive deep into Python data structures, we recommend our Python Data Structures in Practice course. It contains over 115 exercises on Python’s most used data types – among them lists, tuples, dictionaries, and sets. Otherwise, let’s get started with Python sets! The Fundamentals of Python Sets With Examples At their core, Python sets are containers. This means that they contain multiple elements. To create a Python set, we use curly braces and pass in elements separated by commas. In the example below, we initialize a Python set that contains a variety of numbers as its elements: S = {3, 7, 10, 15, 22} Cool! We know how to create a set in Python. But what exactly are Python sets? In a single sentence, Python sets are mutable data structures that contain unique, immutable, unordered elements. Let’s figure out what each of these properties mean! Python Sets Are Mutable As a mutable data structure, a Python set can dynamically change the elements it contains. This behavior is on par with most other data structures in Python, such as lists and dictionaries. In the example below, we start with an empty set and sequentially put new elements in it using the .add() method: S = set() # Creates an empty set S.add(10) S.add(3.0) S.add("Hello") print(S) # output: # {10, 3.0, "Hello"} As we can see, the set S now contains every element that was added to it – despite being initialized as an empty set. Python Sets Have Unique Elements Elements in a Python set are unique. This means that creating a set with duplicates or attempting to add a repeated element to a set effectively does nothing. This behavior is a sharp contrast to Python lists, which accept duplicate values. The example below makes this clear – the attempt to add the value 10 multiple times to the set S does not work: S = {10} S.add(10) S.add(20) S.add(10) print(S) # output: # {10, 20} Elements in Python Sets Must Be Immutable Additionally, even though they are mutable, the elements in Python sets must have an immutable data type. Mutable data types, like lists and dictionaries, cannot be added to sets. In fact, trying to do so will raise a TypeError: S = {10} some_list = [1, 2, 3] S.add(some_list) # TypeError: unhashable type: 'list' Python Sets Are Unordered Finally, Python sets are unordered. This means that, unlike with lists, you cannot ask for the “first” or “last” element in a Python set. You also cannot expect elements to come up in any particular order when iterating over a Python set. In the example below, note how the order in which we added the elements to the set isn’t the same when we iterate over it. The order might even differ if you run the code in your own machine: S = set() # Empty set S.add('???') S.add('abc') S.add(5) S.add('Hello') for element in S: print(element) # Output: # 5 # Hello # abc # ??? If you’d like to remind yourself of the properties of the other data structures, here’s an article on the differences between lists, tuples, and sets. Performing Basic Set Operations with Python Sets Python sets are often used alongside specific operations known as set operations. Set operations are used to combine and filter values in a variety of ways. We will go over the most common Python set operations, with some examples that represent each operation. You can also check out our other articles, if you want a deeper dive in set operations. Combining Elements With Set Union Set union is used to combine elements from two sets. The resulting set is simply a merge of all values contained in either set: A = {1, 2, 3} B = {2, 4, 6, 1} # using the union method result = A.union(B) # using the union operator result = A | B print(result) # output: # {1, 2, 3, 4, 6} Finding Common Elements With Set Intersection Set intersection is used to find the elements common to both sets. Only elements appearing in all of the input sets are included in the resulting set: A = {1, 2, 3} B = {2, 4, 6, 1} # using the intersection method result = A.intersection(B) # using the intersection operator result = A & B print(result) # output: # {1, 2} Finding Elements Unique to a Set with Set Difference Set difference is used to find the elements that appear in one set but not the other. Due to the nature of this operation, obtaining the set difference of set A with respect to set B is not the same as calculating the set difference of B with respect to A: A = {1, 2, 3} B = {2, 4, 6, 1} # using the difference method diff_A = A.difference(B) # using the difference operator diff_A = A - B print(diff_A) # output: # {3} The operation above returns a set of these elements from A that aren’t present in B – here, {3} is returned because other elements of A (1 and 2) are present in set B. # using the difference method diff_B = B.difference(A) # using the difference operator diff_B = B - A print(diff_B) # output: # {4, 6} Likewise, the operation above returns a set of these elements from B that aren’t present in A – here, {4, 6} is returned because other elements of B (1 and 2) are present in set A. Examples of Advanced Set Operations in Python So now we know about sets, how to use them, and how set operations work. But why exactly would we use sets, anyway? As it turns out, there are a couple of real-world scenarios where Python sets are extremely handy to have around. Let’s look into some of these situations below! Using Python Sets to Get Unique Values in a Sequence One of the main practical applications of Python sets is to return a list of unique values from any Python sequence, such as a list or tuple. By simply converting a sequence to a set using the set() function and then back to its original data type, we obtain the same object without any duplicate entries. For example: names = ['John', 'James', 'John', 'Jill', 'James'] unique_names = list(set(names)) print(unique_names) # output: # ["Jill", "John", "James"] As we can see, by converting the list names to a set and then back to a list, we have obtained a new list with no duplicates. And remember, the elements in the new list may appear in a different order since sets are unordered. We can leverage this behavior to create a simple function that checks whether a list contains duplicate elements: def has_duplicates(some_list): unique_values = list(set(some_list)) if len(some_list) == len(unique_values): return False else: return True print(has_duplicates([0, 3, 6, 10])) # output: # False print(has_duplicates([0, 0, 1, 2])) # output: # True Using Python Set Operations to Find Values Based on Conditions Imagine you are a biology teacher and you want to figure out which topics your students like the most. You conduct a small survey and end up with the data below (where each student is represented by their corresponding student ID): likes_plants = {6, 12, 15, 18, 23, 24} likes_ecology = {1, 4, 5, 10, 15, 18, 19, 20, 21, 25} likes_genetics = {3, 4, 6, 19, 22} Based on these sets, how could you figure out if there are any students that like only genetics? Or whether there are any students that like all subjects? It’s simple if you use set operations. For example, you can get the set difference between likes_genetics and the other sets to answer the first question: only_likes_genetics = likes_genetics.difference(likes_plants, likes_ecology) print(only_likes_genetics) # output: # {3, 22} On the other hand, any students that like all subjects will be in the set resulting from the intersection of all the sets: likes_all = likes_genetics.intersection(likes_plants, likes_ecology) print(likes_all) # output: # set() Whoops! It looks like none of the students actually like all the subjects. This is just a simple example, but the exact same logic could be applied in any similar scenario. For example, if you have an online store, you could find out which customers live in the US or in Europe, often buy electronics from your shop, and haven’t accessed your website in the last 7 days. As long as you have the data, you can perform any kind of filtering and grouping logic using Python set operations! Want More Python Set Examples? If you still want to learn more about Python sets, we have an article that teaches all you need to know about them. It includes set methods not described in this article, and even the esoteric frozenset object. Alternatively, if you’re feeling a bit stuck in your Python learning journey, we recommend our article on how long it takes to learn Python. And of course, don’t forget to check out our full track and course catalog to find the one that’s right for you! Tags: python sets