Sets in Python

Sets

Sets in python are same as sets in mathematics and Python allows you to perform operations such as union, intersection, Cartesian etc. A set can be created as follows:

name_set = {'Eric','Alex','Lisa','Richard'}
print(name_set)

Download the code Run the code

You can create a set from a list as follows:

name_list = ['Eric','Alex','Lisa','Richard']
name_set = set(name_list)
print(name_set)

Download the code Run the code

Union of two sets

Union is used to combine values of two sets into one set:

set1 = {1,2,3}
set2 = {4,5,6}
set3 = set1.union(set2)
print(set3)

Download the code Run the code

Intersection of two sets

Intersection function delivers a set that has elements that were common in two sets:

set1 = {1,2,3,4}
set2 = {4,5,6}
set3 = set1.intersection(set2)
print(set3)

Download the code Run the code

subset and superset

issubset() is a method that is used to find out whether a set is a subset of the other set or not. The function returns true if it is a subset or else false is returned.

set1 = {1,2,3,4,3,4,5,6,9,10}
set2 = {4,5,6}
if set2.issubset(set1):
    print("set2 is a subset of set1")

Download the code Run the code

issuperset() is a method that is used to find out whether a set is a superset of the other set or not. The function returns true if it is a superset or else false is returned.

set1 = {1,2,3,4,3,4,5,6,9,10}
set2 = {4,5,6}
if set1.issuperset(set2):
    print("set1 is a superset of set2")

Download the code Run the code

<<< Exception Handling in Python
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .