Python Sets Practice Programs For Beginners

Python Sets Practice Programs For Beginners

5 mins read2.4K Views Comment
clickHere
Updated on Sep 20, 2022 09:25 IST

Python offers a rich collection of sequence object types, and sets are one of them.

2022_02_MicrosoftTeams-image-20.jpg

Python sets are unordered collections of unique elements and immutable objects. You can think of them as a dictionary with just the keys and its values thrown away. Therefore, each item of a set should be unique. Alright! Here are simple programs based on sets that will help you get started with sets in Python.

Remember to tackle these questions on your own before checking for solutions!

Input:

List1 = [10, 45, 34, 20, 11]

List2 = [11, 25, 45, 20]

Output:

[10, 34, 25]

In this example, we are first converting the two lists and using the ‘-’ operator to find the difference between them. Alternatively, you can also difference the () method to do the same. Then you can apply list() to convert the dictionaries to list.

 
#difference between two lists- Using set()
def diff_between(list1, list2):
A = set(list1)
B = set(list2)
#return list(A - B) + list(B - A)
return list({*A.difference(B),*B.difference(A)})
# Driver Code
List1 = [10, 45, 34, 20, 11]
List2 = [11, 25, 45, 20]
print(diff_between(List1, List2))
Copy code

Python Program to Check if a Given String Is Heterogram or Not

A string is a heterogram if it has no alphabet that occurs more than once. For example, “NaukriLearning” is not a heterogram. However, “abc def ghi jkl” is a heterogram. You can follow the below steps to check if a given string is a heterogram or not.

  1. Separate all the alphabets from other any other characters (using list comprehension)
  2. Convert list of alphabets into set because set has unique elements (using set())
  3. Check if the length of the set is equal to number of alphabets
  4. If yes, then string is heterogram otherwise its not

Here’s the code! We are using the ord() function which returns the ASCII value. If the ASCII value of the alphabet is greater than or equal to that of ‘a’ and less than or equal to ‘z’ then add it to the list ‘alphabets’

 
#check if string is heterogram or not
#sample string
str1 = "Naurkrilearning"
str2 = "abcd efgh ijkl"
def check_heterogram(input):
# separate out list of all alphabets
list_of_alphabets = [ alph for alph in input if ( ord(alph) >= ord('a') and ord(alph) <= ord('z') )]
# convert into set and compare lengths
if len(set(list_of_alphabets))==len(list_of_alphabets):
print ("Yes, the string '", input, "'is heterogram")
else:
print ("No, the string'", input, "'is not heterogram")
check_heterogram(str1)
check_heterogram(str2)
Copy code

Program in Python to Print Maximum and Minimum Elements

You can use min() and max() functions to achieve this.

 
#find max and min values
#initializing set
set1 = {15, 25, 2, 10, 11, 55}
print("Original set elements:", set1)
print("Maximum value of given set:", max(set1))
print("Minimum value of given set:", min(set1))
Copy code

Python Program to Get All the Subsets of a Given Size in a Set

You can do this in a Pythonic way using loops. However, in this example, let us try to execute it differently. Python has a method called itertools.combinations(iterable, n), which returns n length subsequences of a given iterable.

Here’s the code! In the below code, use itertools.combinations(setn, n) in for loop and then append the resultant sets to the list

 
#get all subset of give size in a set
#importing module itertool which has combinations() method
import itertools
#initializing set and length of sunset
set1 = {1, 2, 3}
n = 2
def get_subsets(setn, n):
return [set(i) for i in itertools.combinations(setn, n)]
print(get_subsets(set1, n))
Copy code

Try executing this by not using any python built-in module. Using loops and creating functions.

Python Program to Determine if Two Sets Are Disjoint or Not Without Using Inbuilt-in Functions

Sets A and B are called disjoint if they do not have any common elements. You can check if two given sets are disjoint or not in multiple ways. In this example, let’s try implementing it without any in-built functions.

 
#Determine if two sets are disjoint or not
# take each item of set1 and search if it is present in set2
# if yes return False
def check_if_disjoint(set1, set2):
counter = 0
# separate out list of all alphabets
for x in set1:
if x in set2:
counter = counter + 1
if counter > 0:
return False
else:
return True
#initializing sets
set1 = {'Python', 'Java', 'Data Science'}
set2 = {'ML', 'AI', 'R Language', 'Python'}
set3 = {'Data Analytics', 'Robotics', 'Deep Learning'}
#printing results
print("Are set1 and set2 disjoint? :", check_if_disjoint(set1, set2))
print("Are set1 and set3 disjoint? :", check_if_disjoint(set1, set3))
Copy code

Program in Python to Remove the Given Items of a Set at Once

You can remove all the elements of a set at once using the clear() method. However, what we really want to do here is remove only the given elements but at once. To do so you can use the set method difference_update(), which will find the uncommon elements of set1 and the set of items to be removed and then update the set1, which is called as the difference_update() method.

 
#removing the given items a once
set1 = {0, 1, 2, 3, 4, 5, 6}
print("Original set1:", set1)
#use difference_update() method
set1.difference_update({2, 3, 6})
print("Result set1:", set1)
Copy code

Python Program to Count Number of Vowels in a Given String Using Sets

You need to write a program that will count the number of vowels in a given string.

 
#count number of vowels
def count_vowels(str1):
#create a set with vowels (both uppercase & lowercase)
vowels = set('aeiouAEIOU')
counter = 0
#check if the each character if string is vowel
#if yes increment the counter
for ch in str1:
if ch in vowels:
counter = counter + 1
#print the count
print("Number of Vowels in Given String = ", counter)
#driver code
string1 = "Shiksha Online"
count_vowels(string1)
Copy code

Program in Python to Convert a Set to String

Let’s do this using the str() method, or join() method as shown below.

 
#Convert a Set to String
print("Converting set to string")
#Initializing set
var1 = {'a', 'e', 'i', 'o', 'u'}
print("The datatype of var1 : " + str(type(var1)))
print("Contents of var1 : ", var1)
# convert a Set to String using str
var2 = str(var1)
print("\nThe data type of var2 : " + str(type(var2)))
print("Contents of var2 : " + var2)
# convert a Set to String using join
var3 = ', '.join(var1)
print("\nThe datatype of s : " + str(type(var3)))
print("Contents of s : ", var3)
Copy code

Check out Python based online courses

Program in Python to Find Common Elements of Three Given Lists Using Sets

You can check this by performing the intersection operation as shown below.

 
#find the common elements in three lists
def find_common(list1, list2, list3):
set1 = set(list1)
set2 = set(list2)
set3 = set(list3)
#first perform intersection on set1 & set2
res_set1 = set1.intersection(set2)
#perform intersection of res_set1 & set3
res_set2 = res_set1.intersection(set3)
#converting to list
#printing the result
end_list = list(res_set2)
print(end_list)
# Driver Code
List1 = [10, 45, 34, 20, 11]
List2 = [11, 25, 45, 20]
List3 = [20, 25, 11, 14, 45, 65]
find_common(List1,List2, List3)
Copy code

Python Program To Square the Elements of Set Using for Loop

The solutions demonstrate how you can iterate through the items of set and square them using loop as well as set comprehensions.

 
#Square elements of set
#Traversing a set
set1 = {0, 1, 2, 3, 4}
print("Original set1:", set1)
#square the elements of set using for loop
res_set = set()
for x in set1:
res_set.add(x*x)
print("Updated copy of set1:", res_set)
#using set comprehension
print("Iterating set through set comprehension:", {x ** 2 for x in [1, 2, 3, 4]})
Copy code

Python Program to Check if a Set Is Superset Itself or Another Given Set

 
#check if set is superset of itself or other given set
# Initializing sets
set1 = {10, 45, 34, 20}
set2 = {10, 45, 34, 20, 11}
set3 = {20, 25, 11, 14, 45, 65}
print("Is set1 superset of itself?:", set1.issuperset(set1))
print("Is set2 superset of set1?:", set2.issuperset(set1))
print("Is set3 superset of set1?:", set3.issuperset(set1))
Copy code

Program in Python to Perform Intersection of Two Lists Using Set Methods

You can use set methods such as set() and intersection() to perform the intersection of two lists as shown below. The solution also shows how to perform this using & operator.

 
# Perform intersection of two lists using set() & intersection()
def perform_intersection(list1, list2):
return set(list1).intersection(set(list2))
def do_intersection(list1, list2):
return list(set(list1) & set(list2))
# Driver Code
List1 = [11, 25, 45, 20]
List2 = [20, 25, 11, 14, 45, 65]
print("Using intersection() method:", list(perform_intersection(List1, List2)))
print("Using set(), & operator:", list(do_intersection(List1, List2)))
Copy code

Python Program To Check If a Given Value is Present in Set or Not

You can check for an item in the string using in operator as shown below.

 
#check if a given item is present in set or not
set1 = {10, 45, 34, 20}
#original set
print("The original set:", set1)
#check if present or not using 'in'
print("Is 6 present in set1:", 6 in set1)
print("Is 20 present in set1:", 20 in set1)
Copy code

That’s it, folks! I hope you found these Python programs helpful. If you have any problem statement that you are stuck with please raise a query in the comment section below. Happy coding!

Recently completed any professional course/certification from the market? Tell us what you liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio