Sets - Python

  • varS = {valu1, valu2} => Initialize a set
    • Removes duplicates
    • Unordered collection
    • Unchangeable
  • varS = set() => Creates a empty set
    • varS = {} => Empty set acts as dictionary
  • varS.add(value) => Adds in the set, Retains only unique values
  • varS.remove(value) => Removes the value given from the set if it is present otherwise throws error
    • varS.discard(value) => Removes an element from the set if it is present
    • If the element is not present, it raises a KeyError exception
  • varS.pop() => Removes and returns an arbitrary element from the set
    • If the set is empty, it raises a KeyError exception
  • max(varS) => Return maximum element of set
  • min(varS) => Return minimum element of set
  • len(varS) => Return length of set
  • varS.clear() => Removes all elements from the set
    • del varS => Deletes the entire set
  • varS.copy() => Returns a shallow copy of the set
  • varS.update(varS1) => Adds all elements from varS1 to the set
  • varS.issubset(varS1) => Returns True if the set is a subset of varS1
  • varS.issuperset(varS1) => Returns True if the set is a superset of varS1
  • varS1.isdisjoint(varS2) => Returns True if both sets are disjoint
  • varS.union(varS1) => Returns union of varS and the new set given
  • varS.difference(varS1) => Returns a new set that is the difference between both sets
  • varS.difference_update(varS1) => Removes all elements from the set that are also present in varS1
  • varS.intersection(varS1) => Returns intersection of varS and the set given
  • varS.intersection_update(varS1) => Removes all elements from the set that are not present in varS1
  • varS.symmetric_difference(varS1) => Returns a new set that is the symmetric difference between the set and varS1
    • The symmetric difference is defined as the set of elements that are present in either the original set or other set, but not both
  • varS.symmetric_difference_update(varS1) => Removes all elements from the set that are also present in varS1, and adds all elements that are present in varS1 but not in the set
  • Loop Elements
        for element in varS:
            print(element)
    
  • Checks if element is present in the set
        if value in varS:
            # statements
        else:
            # statements
    
Share: