Python | Access Items in Set



Python | python access item in set

You cannot access items in a set by referring to an index 

But you can for loop through print the items ,by using 'in' Keyword

Example

    set = {'mango' ,' banana', 'graps' , 'apple', 'mango'}
    
    for x in set:

        print(set)        

Output

    mango
    banana
    apple
    graps



'del' Keyword

'del' keyword is delete all items from set 

Example

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

    del set

    print(set)        


Output

    <class 'set'>


Loop Through set

for loop

using for loop print the value one by one

Example

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

    for x in set:

        print(x)        

Output

    graps
    mango
    apple


concate set

there are several methods for concatenation of two sets

union() method:

you can use union() method for join two or more sets, return combine sets

Example 

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

    print(set1.union(set2))        


Output

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


update() method

using the update() method, insert set2 into set1
 
Example 

    set1 = {'mango' ,' banana', 'graps' , 'apple', 'mango'}
    set2 = {'papaya','orange'}
    set1.update(set2)
    
     print(set1)        

Output

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

Post a Comment (0)
Previous Post Next Post