Python Sets

Set
A set in Python is collection of data which is unorederd and unindexed. You can create the sets in python with the help of curly brackets. For better understanding consider the following example:

thisset = {"apple", "banana", "cherry"}

print(thisset)


Access Items
As we now know that sets have unorederd items so they do not have any index and that is the reason that we cannor access the elements of the set by reffering to the index of the set.

But, besides this you can loop through the elements of the set using for loop, or you can check for a specified value if it is present in a set with the help of in keyword.

thisset = {"apple", "banana", "cherry"}

for x in thisset:

     print(x)


Change Items
If once you have created a set then you cannot chage the values of the set but one thing that you can do with the sets is that you can add the elements in set unlike tuples in which ou cannot add the elements.

Add Items
If you want to add the items in a set then you can use the add() ethod for that.
If you want to add more than one item in a set then you can use the update() method for that.

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)


Get the Length of a Set
If you want to determine the length of a set i.e. you want to find that how many elements are present in a set then you can use the len() method for that.

thisset = {"apple", "banana", "cherry"}

print(len(thisset))


Remove Item
If you want to remove an item from a set then you can use the remove() or the dicard() method for that.

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)


The set() Constructor
If you want to generate a set with the help of a function then you can use the set() method for that. This method will generate a set automatically for you.

thisset = set(("apple", "banana", "cherry"))

print(thisset)