31. Problem to find the common elements between two sets

In this Python set program, we will find the common elements between two sets 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.

Common elements between two sets:

Steps to solve the program

1. Create two sets using {}.
2. Add some elements in the set.
3. Use a for loop to iterate over elements in the first set.
4. Use an if statement to check whether the element is in the second set.
5. If yes then print that element.

				
					a = {1,2,4,5}
b = {4,1}
print("Original set1: ",a)
print("Original set2: ",b)
print("Common elements: ")
for ele in a:
    if ele in b:
        print(ele)
				
			

Output :

				
					Original set1:  {1, 2, 4, 5}
Original set2:  {1, 4}
Common elements: 
1
4
				
			

Related Articles

check if a set is a superset of another set.

remove a specific element from a set.

Leave a Comment