Python Sets
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.
When you execute the above python program, you will get the result as shown below.
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.
learn
elysium
10
20
30
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, "elysium", "learn"}
st.add(30)
st.add("python")
print(st)
The above python set example will return the result as shown below.
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.
Following is the example of removing the set items based on the value using the set discard() method.
Following is the example of using the set pop() method to remove set items.
Following is the example of removing all the set elements using the clear() method in python.
Following is the example of using the len() function in python to get the set length/size.
st = {}
cnt = len(st)
if cnt > 0:
print("Set size: ", cnt)
else:
print("Set is empty")
The above set example will return the result as shown below.
Set is empty
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, "elysium"}
st2 = {10, "learn", "python"}
st3 = st1.union(st2)
print(st3)
The above set example will return the result as shown below.
Following is the example to verify whether the particular exists in the set or not using in operator in python.
20 in set: True
tutlane in set: True
50 in set: False
Following is the example of getting the common items from defined sets using the intersection() method in python.
{10}
Following are some of the commonly used built-in set methods available in the python programming language.
Method Description
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.