Understanding Python Sets (With Examples)
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.
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.
Table of Contents
Best-suited Python courses for you
Learn Python with these high-rated online courses
Creating Sets
#Example 1set1 = 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)
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 errorprint(5 in set1)
#Example 3: Adding an item to set & modifying the setset1 = {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 setset1.update([0, 6, 9], {7, 8} )print("Updated version 2 of set1:", set1)
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 itemsset1 = {0, 1, 2, 3, 4, 5, 6}print("Original set1:", set1) #discard an elementset1.discard(4)print("Updated version 1 of set1:", set1) #remove an elementset1.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 unchangedset1.discard(7)print("Updated version 3 of set1:", set1)
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 itemsset1.clear() print(set1)
#Example 6: Traversing a setset1 = {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 comprehensionprint("Iterating set through set comprehension:", {x ** 2 for x in [1, 2, 3, 4]})
#Example 7: Copying a setset1 = {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)
#Example 8: Combining Setsset1 = {1, 2, 7}set2 = {5, 8}set3 = {0, 6} #using unionres_set1 = set1.union(set2)print("Resulting set 1:", res_set1) #using union for multiple setsres_set2 = set().union(set1).union(set2).union(set3)print("Resulting set 2:", res_set2) #using updateset2.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)
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 Operationsset1 = {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))
#Example 1: Mathematical Set Operationsset1 = {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)) #issupersetprint("Is set2 superset of set3? :", set2.issuperset(set3))print("Is set4 superset of set2? :", set4.issuperset(set2))
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)
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.
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