Sets

A set an unordered collection of items. Every element is unique and which are immutable. Set elements are enclosed in curly braces {}.

Create a set

#creating set with elements
set1 = {1,2,3,4}
#creating empty set
set2 = set()

Set Operations: Let us consider the following sets:

setA = {1,2,3,4,5}
setB = {4,5,6,7,8}

  1. Union: It is a set of all elements from both sets. Union is performed using | operator.

    setA = {1,2,3,4,5}
    setB = {4,5,6,7,8}
    print(setA|setB)

    {1, 2, 3, 4, 5, 6, 7, 8}

  2. Intersection: It is a set of elements that are common in both sets. Intersection is performed using & operator.

    setA = {1,2,3,4,5}
    setB = {4,5,6,7,8}
    print(setA&setB)

    {4,5}

  3. Difference: It is a set of elements that are only in setA but not in setB. Difference is performed using - operator.

    setA = {1,2,3,4,5}
    setB = {4,5,6,7,8}
    print(setA-setB)
    print(setB-setA)

    {1,2,3}
    {6,7,8}

  4. Symmetric Difference: It is a set of elements in both setA and setB except those are common in both. Symmetric difference is performed using ^ operator.

    setA = {1,2,3,4,5}
    setB = {4,5,6,7,8}
    print(setA^setB)

    {1, 2, 3, 6, 7, 8}

Set Methods:
  1. add()
  2. clear()
  3. copy()
  4. difference()
  5. difference_update()
  6. discard()
  7. intersection()
  8. intersection_update()
  9. isdisjoint()
  10. issubset()
  11. issuperset()
  12. pop()
  13. remove()
  14. symmetric_difference()
  15. symmetric_difference_update()
  16. union()
  17. update()