Understanding Python Sets (With Examples)

Understanding Python Sets (With Examples)

4 mins read748 Views Comment
clickHere
Updated on Sep 24, 2022 14:37 IST

In this article, you will discuss about Python Sets: creating sets, accessing, adding, and removing set items, looping through a set, and other set operations with the help of examples.

2022_02_Python-Sets.jpg

Sets are unordered collections of unique elements and immutable objects. You can think of them as a dictionary with just the keys and their values thrown away. Each item of a set should be unique. While sets themselves can be mutable, that is you can add or remove items, however, the items of a Python set must be of an immutable type.

#Example 1
set1 = set([2, 3, 4, 4, 5, 5, 6])
print("The set1 has:", set1)
set2 = {2, 2, 3, 4, 5, 5, 6, 6, 6, 7}
print("The set2 has:", set2)
Copy code

You can create a set using the set() function or via a set literal with curly brackets. Python provides two set types, the mutable type:set and the immutable type: frozenset. Sets are basically used to perform set operations that you might be familiar with such as intersection, union, complement, and difference. You should know that, unlike sequence types that we learned earlier, set types do not provide any indexing or slicing operations because they are unordered.

Accessing Set Items

You actually cannot access elements of the set using an index or a key. However, you can check if a particular item is present in a set using the in operator.

 
#Example 2:
set1 = {2, 3, 4, 5, 6, 7}
#accessing sets
#set1[4] -> will throw you an error
print(5 in set1)
Copy code

Add or Change Set Items

You can add an element to the set using the add() method as shown below. The example below also demonstrates how you can update the set items using update().

 
#Example 3: Adding an item to set & modifying the set
set1 = {1, 4}
print("Original set1:", set1)
#adding an element using add()
set1.add(2)
print("Updated version 1 of set1:", set1)
#updating the set items using update()
set1.update([3, 5])
print("Updated version 2 of set1:", set1)
#adding a list & a set
set1.update([0, 6, 9], {7, 8} )
print("Updated version 2 of set1:", set1)
Copy code

Removing Elements of Set

Removing items using discard( ) & remove( )

To remove an element of a set you can use methods such as discard() & remove(). The only difference is that the discard() function leaves a set unchanged if the item is not present. Whereas, the remove() function will raise an error.

 
#Example 4: Remove set items
set1 = {0, 1, 2, 3, 4, 5, 6}
print("Original set1:", set1)
#discard an element
set1.discard(4)
print("Updated version 1 of set1:", set1)
#remove an element
set1.remove(3)
print("Updated version 2 of set1:", set1)
#remove non existing element
#set1.remove(7) -> This will raise an error
#discard non existing element - leaves set unchanged
set1.discard(7)
print("Updated version 3 of set1:", set1)
Copy code

Removing items using pop( ) & clear( )

Since sets are unordered, you cannot determine which element of the set will be popped. You can also remove all the items of the set at once using clear()

 
#removing items using pop() & clear()
set1 = {0, 1, 2, 3, 4, 5, 6}
print("Original set1:", set1)
#popping an element using pop()
print("Popped element:", set1.pop())
#clear all the set items
set1.clear()
print(set1)
Copy code

Looping Through a Set

As sets are iterable containers, you can use them in operations such as len, for loops, and list comprehensions.

 
#Example 6: Traversing a set
set1 = {0, 1, 2, 3, 4}
print("Original set1:", set1)
#square the elements of set using for loop
res_set = set()
for x in set1:
res_set.add(x*x)
print("Updated copy of set1:", res_set)
#using set comprehension
print("Iterating set through set comprehension:", {x ** 2 for x in [1, 2, 3, 4]})
Copy code

Copying Set

Just like dictionaries, you will notice that if you make any change to the original set, it will reflect in all the other names that refer to it as well. So to avoid this and make a perfect copy, you can use the copy() method as shown below.

 
#Example 7: Copying a set
set1 = {0, 1, 2, 3, 4}
print("Original set1:", set1)
set2 = set1.copy()
set1.update([6, 8])
print("The updated set1:", set1)
print("The copy of set1, which is set2:", set2)
Copy code

Joining Sets

There are several ways to join Python sets.

  1. union() – returns a new set containing elements from both the given Python sets
  2. update() – adds the items from one set to another
  3. ‘|’ (union operator) – works just like union
  4. Using unpacking operator *
 
#Example 8: Combining Sets
set1 = {1, 2, 7}
set2 = {5, 8}
set3 = {0, 6}
#using union
res_set1 = set1.union(set2)
print("Resulting set 1:", res_set1)
#using union for multiple sets
res_set2 = set().union(set1).union(set2).union(set3)
print("Resulting set 2:", res_set2)
#using update
set2.update(set3)
print("Updated set2:", set2)
#using |
print('Join set1 and set2:', set1 | set2)
print('Join set2 and set3:', set2 | set3)
#using *
res_set3 = (*set1, *set2, *set3)
print("Resulting set 3:", res_set3)
Copy code

Set Methods

Set object type has a lot of methods. Let’s divide them into categories and learn.

Mathematical Set Operations

Method Description
union() Returns a new set with all unique elements from both the sets
intersection() Returns a set consisting of all the unique elements that the two sets have in common
difference() Returns a set that elements of set1 that are not present in set2
symmetric_difference() Returns a set with elements from both the sets that are not in common with one another
isdisjoint() Returns True if two sets are disjoint (if they do not have common elements), else returns false
 
#Example 9: Mathematical Set Operations
set1 = {1, 2, 2, 3, 4}
set2 = {3, 3, 4, 4, 5}
#union()
print("Union:", set1.union(set2))
#intersection()
print("Intersection:",set1.intersection(set2))
#difference()
print("Difference:",set1.difference(set2))
#Symmetric difference()
print("Symmetric difference:", set1.symmetric_difference(set2))
print("Symmetric difference:", set2.symmetric_difference(set1))
#disjoint()
print("set1 disjoint set2:", set1.isdisjoint(set2))
print("set2 disjoint set1:", set2.isdisjoint(set1))
Copy code

Methods for Comparing Sets

Method Description
a.issubset(b) Tests if each element of a is in b
b.issuperset(a) Checks if each element of a is present in b..ie if b is a superset of set or not
 
#Example 1: Mathematical Set Operations
set1 = {1, 2}
set2 = {4, 2, 1}
set3 = {2, 1}
set4 = {4, 1, 3, 6}
#issubset()
print("Is set1 a subset of set3? :", set1.issubset(set3))
print("Is set2 a subset of set3? :", set2.issubset(set3))
#issuperset
print("Is set2 superset of set3? :", set2.issuperset(set3))
print("Is set4 superset of set2? :", set4.issuperset(set2))
Copy code

Set of Lists

As you know Python sets themselves can be mutable, that is you can add or remove items, however, the items of a set must be of an immutable type. So, it is not possible to create a set of lists. You can have a set of tuples though.

 
#Example 1: Set of lists (Not Possible as sets are mutable)
list1 = [[1, 2, 3], [2, 4, 5], [1, 2, 3], [2, 4, 5]]
set(tuple(x) for x in list1)
Copy code

That’s it, folks! I hope the topics were simple to understand.

Top Trending Tech Articles:
Career Opportunities after BTech | Online Python Compiler | What is Coding | Queue Data Structure | Top Programming Language | Trending DevOps Tools | Highest Paid IT Jobs | Most In Demand IT Skills | Networking Interview Questions | Features of Java | Basic Linux Commands | Amazon Interview Questions

Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio