Thursday, February 13, 2020

Sets

Set is a collection of distinct elements same as we have in mathematics.

How can set help us?
If we have a list with duplicate items and we need a list with a unique item then convert the list to a set. We can also find union, intersection or difference between two sets.

Find unique elements
# Get the unique list
num_list = [1, 2, 3, 4, 2, 2, 3, 1]
num_list = set(num_list)
print(num_list)


{1, 2, 3, 4}

Add an element in the set
# Add a list of elements
new_items = [5, 6, 7, 8]
num_list.update(new_items)
print(num_list)


{1, 2, 3, 4, 5}

Add a list of elements
# Add a list of elements
new_items = [5, 6, 7, 8]
num_list.update(new_items)
print(num_list)


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

Now, let's perform some basic operation on two sets such as union, intersection and difference of these sets.

Union
# union of two sets
set_a = {1, 2, 3, 4}
set_b = {2, 4, 6, 8}
print(set_a.union(set_b))


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

Intersection
# intersection of two sets
set_a = {1, 2, 3, 4}
set_b = {2, 4, 6, 8}
print(set_a.intersection(set_b))


{2, 4}

Difference
# difference of two sets
set_a = {1, 2, 3, 4}
set_b = {2, 4, 6, 8}
print(set_a - set_b)


{1, 3}

Let's try to find out if a set is subset or superset of a given set.
Subset
# subset
set_1 = {1, 3, 5}
set_2 = {1, 2, 3, 4, 5, 6}
set_3 = {1, 3, 5, 7}
print('set_1 is subset of set_2:', set_1.issubset(set_2))
print('set_3 is subset of set_2:', set_3.issubset(set_2))


set_1 is subset of set_2: True
set_3 is subset of set_2: False

Superset
# superset and subset
set_1 = {1, 3, 5}
set_2 = {1, 2, 3, 4, 5, 6}
set_3 = {1, 3, 5, 7}
print('set_3 is superset of set_2:', set_3.issuperset(set_2))


set_3 is superset of set_2: False

No comments:

Post a Comment