Set Comparisons in Python

Set comparisons are used to validate whether one set fully exists within another

  • issubset()
  • issuperset()
  • isdisjoint()

Subset

set2.issubset(set1) Returns True if all elements of second set are in first set. Else, False

Example – 1

Code:

set_1 = {'a', 1, 3, 5}
set_2 = {'a', 1}
is_subset = set_2.issubset(set_1)
print(is_subset)

Output

True

Example – 2

Code

set_1 = {4, 6}
set_2 = {2, 6}
is_subset = set_2.issubset(set_1)
print(is_subset)

Output

False

SuperSet

set1.issuperset(set2) Returns True if all elements of second set are in first set. Else, False

Example – 1

Code

set_1 = {'a', 1, 3, 5}
set_2 = {'a', 1}
is_superset = set_1.issuperset(set_2)
print(is_superset)

Output

True

Example – 2

Code

set_1 = {4, 6}
set_2 = {2, 6}
is_superset = set_1.issuperset(set_2)
print(is_superset)

Output

False

Disjoint Sets

set1.isdisjoint(set2) Returns True when they have no common elements. Else, False

Code

set_a = {1, 2}
set_b = {3, 4}
is_disjoint = set_a.isdisjoint(set_b)
print(is_disjoint)

Output

True

Related Posts

Python Program to Convert Integer into a Single Numeral

Single Digit Number Ram is given a positive integer N .He wishes to convert this integer into a single numeral. He does so by repeatedly adding the…

Python Program to Print Armstrong numbers between two intervals

Write a program to print all the Armstrong numbers in the given range A to B (including A and B). An N – digit number is an…

Python Program to Check if Given Input is a Letter, Digit or Special Character

Letter, Digit or Special Character You are given a character as input. Check if the given input is a Lowercase Letter or Uppercase Letter or Digit or…

Interleave Strings | Python Program to merge two strings by adding characters in alternating order

Interleave Strings Given two strings, write a program to merge the given two strings by adding characters in alternating order, starting with the first string. If a…

Python Program to Check if given colors are present in the color palate

Shekhar is an artist. He likes to draw and paint. He is now drawing a portrait of a city road which is in the black color and…

Python Program to Check the eligibility criteria for donor  

Python Comparison Operators An XYZ hospital has organised a blood donation camp. The eligibility criteria for donor was as follows  1) Age>=18  2) Weight >=50 kg  3)…

Leave a Reply

Your email address will not be published.