Python Devlopment






Sets



2.7 . Sets:

    A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.

       

sets = {"Apple", 10.4, 10}
print(sets)

Output:    
    {"Apple", 10.4, 10}

2.7.1 Accessing Elements:

    You cannot access elements in a set by referring to an index But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.        

sets = {"Apple", 10.4, 10}        
for x in sets:              
    print(x)

Note: Once a set is created, you cannot change its items, but you can add new items.

 

2.7.2 Add Items:

To add one item to a set use the add() method.

To add more than one item to a set use the update() method.

Example: Using add() method

   

sets = {"Apple", 10.4, 10}    
sets.add("Mango")    
print(sets)

Example: Add multiple items to a set, using the update() method:

  

sets = {"Apple", 10.4, 10}    
sets.update(["orange","grapes"])    
print(sets)

2.7.3 Remove Item:

To remove an item in a set, use the remove(), or the discard() method.

Example:Remove "banana" by using the remove() method:

sets = {"Apple", 10.4, 10}
sets.remove(10.4)
print(sets)  

Element 10.4 will be deleted

Example: Remove "Apple" by using the discard() method:

sets = {"Apple", 10.4, 10}    
sets.discard("Apple")    
print(sets) 

Example: Remove the last item by using the pop() method:

  

sets = {"Apple", 10.4, 10}    
x = sets.pop()    
print(x)    print(sets)