A Set can be defined as a unordered and unindexed collection of objects.
As sets are unordered so we cannot be sure about the order in which the items will appear.
In Python. sets are used to written by curly brackets{ }
set1={"Physics","Chemistry","Maths"}
print(set1)
Output:
{'Chemistry','Physics','Maths'}
the set is unordered, meaning: the items will appear in a random order.
Set items cannot be accessed because as we discussed sbove the order in which the items will appear is random.So it will change when you run again and again for output.
To add a single item in set we use add() method.
set1={"Physics","Chemistry","Maths"}
set1.add("English")
print(set1)
Output:
{'Maths','Physics','English','Chemistry'}
To add multiple items in the set we use update() method.
set1={"Physics","Chemistry","Maths"}
set1.update(["English","Computer","Hindi"])
print(set1)
Output:
{'English','Computer','Chemistry','Physics','Maths','Hindi'}
We use the len() function to acheck the length of the given set.
Example:set1={"Physics","Chemistry","Maths"}
print(len(set1))
Output:
3
To remove an item from the set, we can use remove() or discard() method.
Example:set1={"Physics","Chemistry","Maths"}
set1.remove("Chemistry")
print(set1)
Output:
{'Physics','Maths'}
set1={"Physics","Chemistry","Maths"}
set1.discard("Maths")
print(set1)
Output:
{'Physics','Chemistry'}
Note:You can also use pop() method to delete an elemeent but it will delete the last element from the set.
Set consists of some important methods which are very useful.
The clear() method is used to empties the set. This means this will remove all the items from the set.
set1={"Physics","Chemistry","Maths"}
set1.clear()
print(set1)
Output:
set()
The update() method is used insert the items of set2 in set1.
Example:set1={"Physics","Chemistry","Maths"}
set2={1,2,3}
set1.update(set2)
print(set1)
Output:
{1,2,3,'Physics','Maths','Chemistry'}
This method is used to join the 2 sets and give the result in another set.
Example:set1={"Physics","Chemistry","Maths"}
set2={1,2,3}
set3=set1.union(set2)
print(set3)
Output:
{1,2,3,'Chemistry','Physics','Maths'}
There are so many more set methods are available which are very useful.