Python Set Operations With Examples

 

Set Operations

Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Union

Union of two sets is a set containing all elements of both sets.

set_a | set_b

or

set_a.union(sequence)

union() converts sequence to a set, and performs the union.

Example 1

set_a = {4, 2, 8}
set_b = {1, 2}
union = set_a | set_b
print(union)

Output

{1, 2, 4, 8}

Example 2

set_a = {4, 2, 8}
list_a = [1, 2]
union = set_a.union(list_a)
print(union)

Output

{1, 2, 4, 8}

Intersection

Intersection of two sets is a set containing common elements of both sets.

set_a & set_b

or

set_a.intersection(sequence)

intersection() converts sequence to a set, and perform the intersection.

Example 1

set_a = {4, 2, 8}
set_b = {1, 2}
intersection = set_a & set_b
print(intersection)

Output

{2}

Example 2

set_a = {4, 2, 8}
list_a = [1, 2]
intersection = set_a.intersection(list_a)
print(intersection)

Output

{2}

Difference

Difference of two sets is a set containing all the elements in the first set but not second.

set_a – set_b

or

set_a.difference(sequence)

difference() converts sequence to a set.

Example 1

set_a = {4, 2, 8}
set_b = {1, 2}
diff = set_a - set_b
print(diff)

Output

{8, 4}

Example 2

set_a = {4, 2, 8}
tuple_a = (1, 2)
diff = set_a.difference(tuple_a)
print(diff)

Output

{8, 4}

Symmetric Difference

Symmetric difference of two sets is a set containing all elements which are not common to both sets.

set_a ^ set_b

or

set_a.symmetric_difference(sequence)

symmetric_difference() converts sequence to a set.

Example 1

set_a = {4, 2, 8}
set_b = {1, 2}
symmetric_diff = set_a ^ set_b
print(symmetric_diff)

Output

{8, 1, 4}

Example 2

set_a = {4, 2, 8}
set_b = {1, 2}
diff = set_a.symmetric_difference(set_b)
print(diff)

Output

{8, 1, 4}

Comments

Popular posts from this blog

CODING ASSIGNMENT 4

CODING PRACTICE 11 Music Page

CCBP Static Website Coding Assignment 2 Solution | Yoga Page