Python | Set Method and Function

Python | Set Methods and Functions

Len() Function

Len() used for get the length of set


Example

    set = {'mango' ,' banana', 'graps' , 'apple', 'mango'}

    print(len(set))        


Output

    4



Type() Function

 type() is used for to get a type of set


Example

    set = {'mango' ,' banana', 'graps' , 'apple'}

    print(type(set))        


Output

    <class 'set'>



Add Items

add() Method

once created Set , you cannot any change in set but you can add items
add() method is used for add one item in set


Example

    set = {'mango' ,' banana', 'graps' , 'apple', 'mango'}
    set.add("orange")
    
    print(set)     

Output

    {'mango', 'apple', 'graps', 'orange', ' banana'}


update() Method

update() Method is used for add set in current set

Example

    set1 = {'mango' ,' banana', 'graps' , 'apple', 'mango'}
    set2 = {'orange','papaya'}

    set1.update(set2)

    print(set1)        

Output

        {'graps', 'apple', 'papaya', 'orange', 'mango', ' banana'}


Remove Items

remove() and discard() Method for remove the item from set

Example

    set = {'mango' ,' banana', 'graps' , 'apple', 'mango'}
    

    set.remove(' banana')

    print(set)        


Output

        {'apple', 'graps', 'mango'}


If remove item is not exist in set then remove() Method is return an Error

Example

    set = {'mango' , 'graps' , 'apple', 'mango'}
    

    set.remove(' banana')

    print(set)        


Output

     Traceback (most recent call last):
     File "./prog.py", line 2, in <module>
     KeyError: ' banana'


discard() Method
Remove item by discard() Method

Example

    set = {'mango' ,'banana', 'graps' , 'apple', 'mango'}
    

    set.remove('banana')

    print(set)        

Output

    {'apple', 'graps', 'mango'}


If remove item is not exist in set then discard() method  is not return an Error


Example

    set = {'mango', 'graps' , 'apple', 'mango'}
    

    set.discard('banana')

    print(set)        # Return {'apple', 'graps', 'mango'}


Output

    {'apple', 'graps', 'mango'}



pop() Mtehod

pop() Methods will remove item from last of set item but set is unordered so you will not know
what item that get remove

Example

    set = {'mango', 'graps' , 'apple', 'mango'}
    
    set.pop()

    print(set)         

Output

    {'mango', 'graps'}



clear() Method

clear() method is remove all item from set

Example

    set = {'mango', 'graps' , 'apple', 'mango'}
    

    set.clear()

    print(set)       


Output

    set()
Post a Comment (0)
Previous Post Next Post