Subsets of set python

Code Destine

Python Set Subset

Python Set Subset

In this tutorial, we will learn about different ways of checking subset relationship in a given pair of sets.

Subset Set:

In set theory, a set B is a subset of a set A, if B is contained inside A which means that all elements of a set B are also elements of a set A. For example :

A = B = Here, B is subset of A : B ⊆ A 

Python Set issubset

Python Set Subset :

In Python, there are two different ways of checking whether a given pair of sets are in a subset relationship or not, they are as follows :

issubset method :

This method takes iterable (list, tuple, dictionary, set and string) as an argument, if iterable other than set is passed, it first converts the iterable object to set object and then checks whether all elements of a set ( on which issubset method is invoked ) are also present in a set ( passed as an argument ). If yes then it will return True otherwise it will return False.

Example:

# Python Set Subset # create first set object and assign it to variable A A = <1,2,3,4,5,6,7,8,9,10,11,12># create second set object and assign it to variable B B = # call issubset() to check if B is Subset of A? print(‘B is Subset of A?’,B.issubset(A)) # call issubset() to check if A is Subset of B? print(‘A is Subset of B?’,A.issubset(B)) # create a list object and assign it to variable L L = [4,3,7,8,11,12,13] # call issubset() to check if B is Subset of L? print(‘B is Subset of L?’,B.issubset(L))

This operator is used check whether a given pair of sets are in a subset relationship or not just like issubset() method. The difference between and issubset() method is that, the former can work only with set objects while latter can work with any iterable.

Syntax : < Set Object 1 > < Set Object 2 >: To check subset relationship

Example:

# Python Set Subset # create first set object and assign it to variable A A = <1,2,3,4,5,6,7,8,9,10,11,12># create second set object and assign it to variable B B = # create second set object and assign it to variable C C = <1,2,3,4,5,6,7,8,9,10,11,12># use

References :-

That’s all for Python Set Subset with Example. If you liked it, please share your thoughts in comments section and share it with others too.

Источник

Читайте также:  Java or php web development
Оцените статью