What is Set Operation in python with Example

Set{}

A set is another type of collection data type. A Set is a mutable and unordered collection of elements without duplicates. That means the elements within a set cannot be repeated.

A set is created by placing all the elements separated by a comma within a pair of curly brackets { }.

Syntax of set:

variable={element1,element2,element3}

Set Operations

As you learned in mathematics, python has also supported the set operations such as

  • Union
  • Intersection
  • Difference
  • Symmetric difference

Union ( | )

The union includes all elements in two or more sets. That is all element in the given set is returned without duplicate.

In python, the operator | is used to the union of two sets. The function union( ) is also used
to join two sets in python.

Example 1:

  • >>>SET_A = {1,2,3,4,5}
  • >>>SET_B = {5,6,7,8,9,10}
  • >>>print(SET_A | SET_B)
    • {1,2,3,4,5,6,7,8,9,10}

Example 2:

  • >>>SET_A = {1,2,3,4,5}
  • >>>SET_B = {6,7,8,9,10}
  • >>>print(SET_A.union(SET_B))
    • {1,2,3,4,5,6,7,8,9,10}

Intersection ( & )

Intersection includes the common elements in two sets. That is, it returns the same element in the given sets.

The operator & is used to intersect two sets in python. The function intersection( ) is also used to intersect two sets in python.

Example 1:

  • >>>SET_A = {1,2,3}
  • >>>SET_B = {2,3,4,5}
  • >>>print(SET_A & SET_B)
    • {2,3}

Example 2:

  • >>>SET_A = {1,2,3}
  • >>>SET_B = {2,3,4,5}
  • >>>print(SET_A.intersection(SET_B))
    • {2,3}

Difference ( – )

The difference includes all elements that are in the first set (SET_A) but not in the second set (SET_B). It returns an element in the first set, that element not in the second one.

The minus (-) operator is used to difference set operation in python. The function difference( ) is also used to difference operation.

Example 1:

  • >>>SET_A = {1,2,3}
  • >>>SET_B = {2,3,4,5}
  • >>>print(SET_A – SET_B)
    • {1}

Example 2:

  • >>>SET_A = {1,2,3}
  • >>>SET_B = {1,2,3}
  • >>>print(SET_A.difference(SET_B))
    • set()

Symmetric Difference (^)

It includes all the elements that are in two sets but not the one that is common to two sets.

The caret (^) operator is used for symmetric difference set operation in python. The function symmetric_difference( ) is also used to do the same operation.

Example 1:

  • >>>SET_A = {1,2,3}
  • >>>SET_B = {2,3,4,5}
  • >>>print(SET_A ^ SET_B)
    • {1,4,5}

Example 2:

  • >>>SET_A = {‘A’,2,3}
  • >>>SET_B = {1,2,3}
  • >>>print(SET_A.symmetric_difference(SET_B))
    • {‘A’,1}

My Previous Post

Accessing index and value in Tuples: https://iterathon.tech//accessing-index-and-value-in-tuples-python/

LEARN LITTLE BY LITTLE TO CHANGE THE TECH WORLD