Sets in python

Python sets

In Python, set is a collection of dissimilar objects separated by comma and are placed in curly braces '{}'.

  • In set, same values are not repeated.
    • No duplicate elements. 

  • All the elements are unique.

      • If the values are repeated then, one value is kept and the remaining repeating values are discarded automatically.
    • Sets are unordered.
    • Sets are unindexed, because the elements gets shuffled after declaration (unordered).

    • The existing elements in set can not be modified or changed.
      • But can be removed.
      • And new elements can be added in set.

    Program

    >>> # No duplicates are allowed in set.
    >>> a = {1, 2, 3, 1, 2, 3, 1, 1, 1}
    >>> print(a)
    {1, 2, 3}
    >>>
    >>> # Sets are unordered.
    >>> z = {9, 6, 2, 3, 1, 47, 8, 5, 65, 69, 78}
    >>> print(z)
    {65, 2, 3, 1, 5, 6, 69, 8, 9, 78, 47}
    >>> # You may get some other order...



    Initialization of set

    There are 2 methods to initialize set.


    Direct way of initializing a set

    Objects are placed in curly braces'{}', for initialization of a set.


    Program 

    >>> a = {1, 2.3, "hi", True}
    >>> print(a)
    {1, 2.3, 'hi'}


    An empty curly brackets represents Python dictionary


    Program

    >>> a = {1, 2, 3}
    >>> type(a)
    <class 'set'>
    >>> b = {}
    >>> type(b)
    <class 'dict'>
    >>> 


    Initialization with set() method

    Collection of objects are given as an argument to the set() built-in function.


    The collection of objects which are passed as an argument should be separated by comma and should be placed in brackets.

    Program

    >>> mix = set([1, 2, 3])
    >>> print(mix)
    {1, 2, 3}
    >>> mix2 = set((1, 2, 3))
    >>> print(mix2)
    {1, 2, 3}
    >>> mixer = set({'Usha', 'Pooja', 'MaxBlade'})
    >>> print(mixer)
    {'Pooja', 'MaxBlade', 'Usha'}


    For declaration of empty set, use the set() method.


    Program

    >>> a = set()
    >>> print(a)
    set()
    >>> type(a)
    <class 'set'>


    Accessing values in set

    Accessing a value using index, is not possible in set. Because they are unordered.


    The only way of accessing values in a set is, by using a for loop.    LEARN MORE...


    Adding elements in set

    In sets, add()  and update() are the two methods to add element/s.


    Set add() method

    An element is added to the set.


    No effect if the element already exists.


    Only one element is passed as an argument to the add() method, in set.


    Program

    >>> a = {"Hello", "world", 2.0}
    >>> print(a)
    {2.0, 'world', 'Hello'}
    >>> a.add(9)
    >>> print(a)
    {9, 2.0, 'world', 'Hello'}


    Set update() method

    More elements are added using this method, in set.


    The elements to be added are declared in list or tuple and are passed as an argument to the update() method.


    Program

    >>> a = {1, 2, 3}
    >>> a.update([4, 5, 6])
    >>> print(a)
    {1, 2, 3, 4, 5, 6}
    >>>
    >>> # If the elements are present then no changes are made
    >>> a.update([3, 2, 5, 1, 2])
    >>> print(a)
    {1, 2, 3, 4, 5, 6}


    Removing element in set

    For removing an element in set, pop(), remove() or discard() method is used.


    Set pop() method

    Remove and return arbitrary element in a set.


    If the set is empty then, KeyError is raised.


    Program


    >>> a = {"hello", "halloween", 2020, 31, "October"}
    >>> print(a)
    {'hello', 2020, 'October', 31, 'halloween'}
    >>> a.pop()
    'hello'
    >>> print(a)
    {2020, 'October', 31, 'halloween'}



    Set remove() method

    Removes the specified element in a set.


    If the element is not a member, then KeyError is raised.


    Program


    >>> print(a)
    {2020, 'October', 31, 'halloween'}
    >>> a.remove(2020)
    >>> print(a)
    {'October', 31, 'halloween'}
    >>> a.remove(31)
    >>> print(a)
    {'October', 'halloween'}
    >>> a.remove(2020)
    Traceback (most recent call last):
      File "<pyshell#33>", line 1, in <module>
        a.remove(2020)
    KeyError: 2020



    Set discard() method

    Removes the specified element in a set.


    If the element is not a member, does nothing.


    Program


    >>> print(a)
    {'October', 'halloween'}
    >>> a.discard("halloween")
    >>> a
    {'October'}
    >>> print(a)
    {'October'}
    >>> a.discard(2020)
    >>> 



    Set clear() method

    This method makes a set empty.

    Program


    >>> a = {1, 2, 3, 4, 5, 6}
    >>> print(a)
    {1, 2, 3, 4, 5, 6}
    >>> a.clear()
    >>> print(a)
    set()



    Copy a set

    The command 'set1 = set2' will not work because, the changes made in set1 will automatically be made in set2. As both the sets will have the same memory location.


    Program


    >>> a = {"Good", "Bye", 2020}
    >>> b = a
    >>> b.add(9)
    >>> print(b)
    {'Good', 2020, 'Bye', 9}
    >>> print(a)
    {'Good', 2020, 'Bye', 9}
    >>> id(a) == id(b)
    True



    That's why the copy() method is used. 

    Program

    >>> a = {"Good", "Bye", 2020}
    >>> b = a.copy()
    >>> b.add(9)
    >>> print(b)
    {'Good', 2020, 'Bye', 9}
    >>> print(a)
    {'Good', 2020, 'Bye'}
    >>> id(a) == id(b)
    False


    Joining set

    There are 2 methods to join sets.

    • union() method
    • update() method

    Here, the '+' operator can not be used for joining the sets.


    Set union() method

    Creates a new set by joining 2 sets.

    Program


    >>> a = {1, 2, 3}
    >>> b = {4, 5, 6}
    >>> c = a.union(b)
    >>> print(c)
    {1, 2, 3, 4, 5, 6}



    Set update() method

    With this method one set is inserted into the another set.


    In this, new set is not created.


    To create a new set by joining two sets use union() method.


    Program()


    >>> a = {1, 2, 3}
    >>> b = {4, 5, 6}
    >>> b.update(a)
    >>> print(b)
    {1, 2, 3, 4, 5, 6}



    Some more methods to learn...

    MethodMeaning
    difference()
    Returns the difference of two sets.
    a.difference(b), common elements
    will be removed from 'a' with respect
    to 'b' and return the copy of remaining
    elements
    difference_update()
    Removes the common elements
    a.difference_update(b),  common
    elements will be removed from
    'a' with respect to 'b'.
    intersection()
    Returns a new set in which each 
    element is present in the two or
    more sets specified.
    intersection_update()
    Removes the elements from one set
    which are not present in another set
    isdisjoint()
    Returns True if both the sets do not
    have any common element
    issubset()
    a.issubset(b), returns True if all the
    elements of set 'a' are present in the
    set 'b'
    issuperset()
    a.issuperset(b), returns True if 'a'  
    contains all the elements of 'b'
    symmetric_difference()
    Returns a new set in which all the 
    elements are taken from both the
    sets, but the elements which are   
    present in both sets are not included
    symmetric_difference_update()
    a.symmetric_difference_update(b),
    Update set by inserting elements 
    of 'b' to 'a' and removing the elements
    which are present in both
     



    Conclusion

    Set is the collection of objects, which are unordered and mutable.

    No duplicate elements (no repetitions of elements).

    In this we have learned all the methods available with Set.





    Previous                          Next

    If you have any query, feel free to ask.

    إرسال تعليق

    If you have any query, feel free to ask.

    Post a Comment (0)