Python is undoubtedly one of the most popular languages today, and in this article, you will learn everything about set in python with the help of examples. We’ll cover topics like creating sets, modifying sets, their methods, and more.
What Is a Set?
Set is a data type in python used to store several items in a single variable. It is one of the four built-in data types (List, Dictionary, Tuple, and Set) having qualities and usage different from the other three. It is a collection that is written with curly brackets and is both unindexed and unordered.Â
A set is mutable, i.e., we can remove or add elements to it. Set in python is similar to mathematical sets, and operations like intersection, union, symmetric difference, and more can be applied.Â
Set Items
Items of a set in python are immutable (unchangeable), do not duplicate values, and unordered. Thus, items in a set do not appear in a stipulated manner, i.e., they can appear in a different order every time it is used. Due to this, set items cannot be referred to by key or index.Â
After a set is created, its items cannot be changed. However, new items can be added. As we mentioned, all set items need to be unique because duplicates are not allowed. Items in a set can be of any data type.
Set items can be of any data type: String, Boolean, tuple, float, int.Â
set1 = {"ab", "bc", "cd"}
set2 = {11, 15, 17, 19, 13}
set3 = {False, False, True}
How to Create a Set in Python
To create a python set, place all elements or items separated by a comma inside curly braces {}. The built-in set() function can also be used to create a set in python. As per definition, a set can have any number and any items. However, mutable elements such as dictionaries, lists, or sets are not allowed as its elements.Â
# creating different types of sets
# Integer set
integer = {11, 12, 23}
print(integer)
# Mixed set
mixed = {10.0, "Hi", (11, 12, 13)}
print(mixed)
Output: (Notice the random order)
More examples:
# set with duplicates
dup = {11, 12, 13, 14, 13, 12}
print(dup)
# set made from a list
lis = set([11, 12, 13, 2])
print(lis)
Output:
How to Modify a Set in Python
Sets, though mutable, are unordered. Thus, there is no scope for indexing. Indexing or slicing cannot change or access an item of a set as a python set does not support it.Â
We use the add() method to add a single element and update() method when multiple elements are to be added. The elements can be of the form lists, tuples, strings, or sets in the update() method. Duplicates are avoided in all cases.Â
# initializing a set
a = {11, 13}
print(a)
# adding an item
a.add(12)
print(a)
# adding multiple elements
a.update([22, 13, 14])
print(a)
# adding list and set
a.update([14, 15], {11, 16, 18})
print(a)
Output:
How to Get the Length of a Set
The len() method is used to determine the number of items a set has. For example:
cars = {"Audi", "BMW", "Chevrolet"}
print(len(cars))
Output:
Various Set Methods (With Their Uses)
Set in python have various methods. We have seen the use of some of the above. Below is a list of all the available methods for the set objects:
- update()- used to update the set with union of others and itself
- add()- used to add a single item to the set
- copy()- used to return a copy of the set
- clear()- used to remove all items of the set
- discard()- used to remove an item from the set. If the item is not an element, then nothing is done
- union()- used to return a new set as a union of sets
- difference()- used to return a new set as the difference of two or more sets
- difference_update()- used to remove intersecting items from this set
- intersection()- used to return a new set as intersection of two sets
- intersection_update()- used to update a set with the intersection of another set and itself
- pop()- used to return and remove an arbitrary set item, KeyError is raised if the set is empty
- remove()- used to remove an item from the set. KeyError is raised if an item is not a member of the set
- issubset()- if another set is contained in this set, return true
- issuperset()- if this set is contained in another set, return true
- isdisjoint()- if the intersection of two sets is null, return true
- symmetric_difference- used to return a new set as the symmetric difference of two setsÂ
- symmetric_difference_update()- used to update a set with the symmetric difference of another set and itselfÂ
Example of various methods:
x = {"pear", "grapes", "kiwi"}Â
x.add("orange")
print(x)
y = {"mango", "banana", "apple"}
x.update(y)
print(x)
x = y.copy()
print(x)
x.clear()
print(x)
y.discard("banana")
print(y)
z = x.union(y)
print(z)
z = x.difference(y)
print(z)
Output:Â
Set() Constructor in Python
As mentioned earlier, in-built set() constructor can also be used to create a set in python. Here’s how:
cars = set(("Audi", "BMW", "Chevrolet")) # double round-brackets are used
print(cars)
Output:
Python Frozenset
A new class having the characteristics of a set in python whose items cannot be changes post assignment is known as Frozenset. Like tuples behave as immutable lists, frozensets behave as immutable sets.Â
As sets are unhashable, they cannot be uses as keys of a dictionary. However, frozensets are hashable and can act as keys of a dictionary.Â
frozenset() function is used to create frozensets. As they are immutable, add and remove item methide aren’t supported. However, the following methods are:
cop(), intersection(), union(), difference(), issubset(), issuperset(), isdisjoint() and symmetric_difference().
Here’s an example:
#initialize frozenset a and b
a = frozenset([11, 12, 13, 14])
b = frozenset([23, 24, 25, 26])
print(a.isdisjoint(b))
print(a.difference(b))
print(a|b)
Output:
As seen above, set in python is an unindexed and unordered collection having unique members. It is necessary to understand the attributes of a collection type before using it. This can increase the security and efficiency of your program.Â
You can master Python with our Post Graduate Program In Full Stack Web Development, and accelerate your development or data science career, starting now! And in case you have any questions or doubts about ‘set in python, you can write it down in the comments section below and our experts will help you out.