In this Python set program, we will show one set is a subset of another set with the help of the below-given steps.
What is set?
Sets are used to store multiple items in a single variable.
The set is one of 4 built-in data types in Python used to store collections of data.
It is an unordered collection data type that is iterable, mutable and has no duplicate elements.
Subset: A subset is a set that contains some elements of the original set.
One set is a subset of another:
Method 1 : Using in-built function
Steps to solve the program
1. Create two sets using {}.
2. Add some elements in the sets.
3. Check if one set is a subset of another set using issubset() function.
4. Print the output.
a = {1,2,4,5}
b = {2,4}
print("Original set1: ",a)
print("Original set2: ",b)
print("b is subset of a: ",b.issubset(a))
Output :
Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a: True
Method 2 : Using Logic
Steps to solve the program
1. Create two sets using {}.
2. Add some elements in the sets.
3. Create count variable and assign its value equal to 0.
4. Use a for loop to iterate over elements in the second set.
5. Use an if statement to check whether the element is in the first set.
6. If yes then add 1 to the count variable.
7. Use an if-else statement to check whether the value of count variable is equal to the length of the second set.
8. If yes then one set is a subset of another, else not.
9. Print the respective output.
a = {1,2,4,5}
b = {2,4}
print("Original set1: ",a)
print("Original set2: ",b)
count = 0
for ele in b:
if ele in a:
count +=1
if count == len(b):
print("b is subset of a")
else:
print("b is not a subset of a")
Output :
Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a