Python-5(Sets)

1.Python Sets :

1.1 introduction :

  • A set is an unordered collection data type with no duplicate elements. Sets are iterable and mutable. The elements appear in an arbitrary order when sets are iterated.
  • Sets are commonly used for membership testing, removing duplicates entries, and also for operations such as intersection, union, and set difference.
  • A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.

Example :

  1. Creating a set
    thisset = {"apple", "banana", "cherry"}      
    print(thisset)
    
    #output
    {'banana', 'cherry', 'apple'}

1.2 Access Items :

  • You cannot access items in a set by referring to an index, since sets are unordered the items has no 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. 

Example :

  1. Loop through the set, and print the values
    thisset = {"apple", "banana", "cherry"}
    
    for x in thisset:
      print(x)
    
    #output
    cherry
    banana
    apple 

1.3 Adding the item :

  • Python set add(element) This will add element to a set:
  •  To add more than one item to a set use the update() method.

Example:

  1. Add an item to a set, using the add() method
    thisset = {"apple", "banana", "cherry"}
    
    thisset.add("orange")
    
    print(thisset)
    
    #output
    {'banana', 'cherry', 'apple', 'orange'}

     

  2. you can pass a list to the update method and this will update the setA with the elements.

     # pass a list with elements 11 and 12 
     setA.update([11, 12])
     # check if setA is updated with the elements.
     print(setA)
    
    #output
        {1, 2, 3, 4, 5, 6, 7, 8, 11, 12, (9, 10)}
     

1.4 Removing item :

  • Python set discard(element) and remove(element) Used to remove element from the set 

Example :

  1. Remove "banana" by using the remove() method:
    thisset = {"apple", "banana", "cherry"}
    
    thisset.remove("banana")
    
    print(thisset)
    
    #output
    {'cherry', 'apple'}
     

 1.5  set() Constructor :

Example :

thisset = set(("apple", "banana", "cherry"))
print(thisset)

#output
{'cherry', 'banana', 'apple'}

 

Posted on by