Python Sets

In python, Set is a collection of an unordered sequence of unique items, and you can store the values of different data types. The set is same as the list and tuple collections, but the only difference is that it will store the unordered sequence values.

 

In python, you can create the set collection by enclosing the list items within braces { } and the set items must be separated by commas.

 

Following is the example of creating the Set with a different type of items in python.

 

# Set with integer types
a = {30, 10, 10, 20}
# Set with string types
b = {"Tutlane", "Learn", "Python", "Tutlane"}
# Set with mix types
c = {30, 10, 10, 20, "tutlane"}
# Empty Set
d = {}
print("a = ", a)
print("b = ", b)
print("c = ", c)
print("d = ", d)

If you observe the above example, we created different sets and printing the set items using print method in python.

 

When you execute the above python program, you will get the result as shown below.

 

a = {10, 20, 30}
b = {'Tutlane', 'Learn', 'Python'}
c = {10, 'tutlane', 20, 30}
d = {}

If you observe the above result, the Set collection has returned the unique elements of the unordered list. In python, you need to remember that the order of items in the Set collection will vary whenever you execute the program.

Access Elements from Set

In python, it’s impossible to access the set elements using index values because it will store the items in an unordered manner. The order of the items will vary every time you execute the program.

 

Using for loop, you can loop through the items of a set and access the items based on your requirements.

 

Following is the example of accessing the set items using for loop in python.

 

st = {10, 20, 30, "tutlane", "learn"}
for item in st:
    print(item)

The above set example will return the result like as shown below.

 

learn
tutlane
10
20
30

Add or Append Items to Set

Once you create the python set, it won’t allow you to change the set item values. Instead, it will allow you to add or append new items to the set using add() or update() methods.

 

The add() method is useful when you want to add only one item at a time to the set(). Following is the example of adding items to the set using the add() method in python.

 

st = {10, 20, "tutlane", "learn"}
st.add(30)
st.add("python")
print(st)

The above python set example will return the result like as shown below.

 

{10, 'python', 'learn', 'tutlane', 20, 30}

If you want to add multiple items at a time to set, use update() method. Following is the example of adding multiple items to the set using update() method.

 

st = {10, 20, "tutlane", "learn"}
st.update([30, "python"])
print(st)

The above python set example will return the result like as shown below.

 

{10, 'tutlane', 'python', 20, 'learn', 30}

Remove Elements from Set

In python, you can delete/remove items from a set using either del keyword, remove(), discard(), pop(), or clear() methods based on our requirements.

 

In python, if you want to remove set items based on the value, you can use the set remove() method.

 

Following is the example of removing the set items based on the value using the set remove() method.

 

st = {10, 20, 30, "tutlane", "learn"}
print("Before: ", st)
st.remove(20)
st.remove("learn")
print("After: ", st)

The above python set example will return the result like as shown below.

 

Before: {'learn', 10, 20, 'tutlane', 30}
After: {10, 'tutlane', 30}

The remove() method will throw an exception when the defined value is not found in the set. The discard() method is same as the remove() method but, the only difference is the discard() method will not throw an exception, even the defined value is not found in the set.

 

Following is the example of removing the set items based on the value using the set discard() method.

 

st = {10, 20, 30, "tutlane", "learn"}
print("Before: ", st)
st.discard(20)
st.discard("learn")
st.discard(50)
print("After: ", st)

The above python set example will return the result like as shown below.

 

Before: {10, 'tutlane', 'learn', 20, 30}
After: {10, 'tutlane', 30}

In python, the set pop() method is also useful to remove the set items, but this method will remove the last item. As discussed, the sets are unordered so, you will not know which item gets deleted.

 

Following is the example of using the set pop() method to remove set items.

 

st = {10, 20, 30, "tutlane", "learn"}
print("Before: ", st)
st.pop(2)
st.pop()
print("After: ", st)

When you execute the above python list program, you will get the result like as shown below.

 

Before: [10, 20, 30, 'tutlane', 'learn']
After: [10, 20, 'tutlane']

If you want to clear or empty set items, you can use the set clear() method.

 

Following is the example of removing all the set elements using the clear() method in python.

 

st = {10, 20, 30, "tutlane", "learn"}
print("Before: ", st)
st.clear()
print("After: ", st)

The above python set example will return the result like as shown below.

 

Before: {10, 'learn', 'tutlane', 20, 30}
After: set()

If you want to delete the set completely, you can use the del keyword. Following is the example of deleting the set using the del keyword in python.

 

st = {10, 20, 30, "tutlane", "learn"}
print("Before: ", st)
del st
print("After: ", st)

The above python set example will return the result like as shown below.

 

Before:  {'tutlane', 'learn', 10, 20, 30}
Traceback (most recent call last):
  File "D:\pythonset.py", line 4, in <module>
    print("After: ", st)
NameError: name 'st' is not defined

Get Length of Set

In python, to count the number of items in the set, use the len() function.

 

Following is the example of using the len() function in python to get the set length/size.

 

st = {10, 10, 20, 20, 30, "tutlane", "learn"}

print("Set Size: ", len(st)) #Set Size: 7

By using len() function, you can also check whether the set is empty or not like as shown below.

 

st = {}
cnt = len(st)
if cnt > 0:
    print("Set size: ", cnt)
else:
    print("Set is empty")

The above set example will return the result like as shown below.

 

Set is empty

Join or Concatenate Sets

In python, the set methods such as union() and update() methods are useful to join or concatenate multiple sets.

 

The union() method will return a new set containing all the items from the mentioned sets and exclude the duplicates.

 

Following is the example of joining the sets using the union() method in python.

 

st1 = {10, 20, "tutlane"}
st2 = {10, "learn", "python"}
st3 = st1.union(st2)
print(st3)

The above set example will return the result like as shown below.

 

{'python', 20, 'tutlane', 'learn', 10}

The update() method will join the sets by inserting all the items of one set into another set. Following is the example of joining the sets using the update() method in python.

 

st1 = {10, 20, "tutlane"}
st2 = {10, "learn", "python"}
st1.update(st2)
print(st1)

The above set example will return the result like as shown below.

 

{20, 'python', 'learn', 'tutlane', 10}

If you observe both union() and update() method example results, the duplicate values have been excluded from the result set.

Check If Item Exists in Set

By using in and not in operators, you can check whether the particular item exists in the set or not.

 

Following is the example to verify whether the particular exists in the set or not using in operator in python.

 

st = {10, 20, 30, "tutlane", "learn"}
print("20 in set: ", 20 in st)
print("tutlane in set: ", "tutlane" in st)
print("50 in set: ", 50 in st)

The above set example will return the result like as shown below.

 

20 in set: True
tutlane in set: True
50 in set: False

Python Set Intersection

If you want to compare and get only the common items from the specified sets, you can use the intersection() method. The intersection() method will compare the defined sets and return the new set with matching elements from the defined sets.

 

Following is the example of getting the common items from defined sets using the intersection() method in python.

 

st1 = {10, 20, "tutlane"}
st2 = {10, "learn", "python"}
st3 = st1.intersection(st2)
print(st3)

The above python set example will return the result like as shown below.

 

{10}

Python Set Methods

In python, the set object has a set of built-in methods to perform different operations like adding items to the set, remove elements from the set, etc., based on your requirements.

 

Following are some of the commonly used built-in set methods available in the python programming language.

 

MethodDescription
add() It is useful to add elements to the set.
pop() It is useful to remove the element from the set.
remove() It is useful to remove the element with the specified value.
discard() It will remove the specified item from the set.
clear() It is useful to remove all the elements from the set.
copy() It is useful to return a copy of the set.
intersection() It will return a set by intersecting the defined sets.
union() It will return a set by combining all the items of defined sets.
update() It will return a set by merging all the items of defined sets.