python


Python Sets


Sets

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{ }


Example:
set1={"Physics","Chemistry","Maths"}
print(set1)
Output:
{'Chemistry','Physics','Maths'}
the set is unordered, meaning: the items will appear in a random order.
Accessing Items of Set

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.


Change Items
  1. Add Items

    To add a single item in set we use add() method.

    Example:
    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.

    Example:
    set1={"Physics","Chemistry","Maths"}
    set1.update(["English","Computer","Hindi"])
    print(set1)
    Output:
    {'English','Computer','Chemistry','Physics','Maths','Hindi'}
  2. Length of the Set
  3. We use the len() function to acheck the length of the given set.

    Example:
    set1={"Physics","Chemistry","Maths"}
    print(len(set1))
    Output:
    3
  4. Remove Items

    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'}

    Example:
    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 methods

Set consists of some important methods which are very useful.

  1. Clear method

    The clear() method is used to empties the set. This means this will remove all the items from the set.


    Example:
    set1={"Physics","Chemistry","Maths"}
    set1.clear()
    print(set1)
    Output:
    set()

  2. Update method

    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'}

  3. Union method

    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.