Python Sets Practice Questions with Solutions

Sets are unordered collections of unique elements in Python. They automatically remove duplicate values and are useful for membership testing, mathematical set operations, and storing unique data. In this Python Sets Practice Questions with Solutions set, you’ll learn how to create sets, add and remove elements, perform set operations, and solve beginner-friendly Python programs.


1. Python Program to Create and Print a Set

Problem Statement

Write a Python program to create a set of five colors and print it.

Python Solution

colors = {"Red", "Blue", "Green", "Yellow", "Black"}

print(colors)

Sample Output

{'Blue', 'Green', 'Yellow', 'Black', 'Red'}

Explanation

A set stores unique values inside curly braces {}. The order of elements may vary.

Concepts Covered

  • Creating Sets
  • Set Syntax

2. Python Program to Add an Element to a Set

Problem Statement

Write a Python program to add "Python" to a set of programming languages.

Python Solution

languages = {"Java", "C++", "JavaScript"}

languages.add("Python")

print(languages)

Sample Output

{'Java', 'Python', 'C++', 'JavaScript'}

Explanation

The add() method inserts a new element into a set.

Concepts Covered

  • add()

3. Python Program to Remove an Element from a Set

Problem Statement

Write a Python program to remove "Orange" from a set.

Python Solution

fruits = {"Apple", "Orange", "Banana", "Mango"}

fruits.remove("Orange")

print(fruits)

Sample Output

{'Apple', 'Banana', 'Mango'}

Explanation

The remove() method deletes the specified element from the set.

Concepts Covered

  • remove()

4. Python Program to Check Whether an Element Exists in a Set

Problem Statement

Write a Python program to check whether "Python" exists in a set.

Python Solution

courses = {"Python", "Java", "SQL"}

if "Python" in courses:
    print("Course Found")
else:
    print("Course Not Found")

Sample Output

Course Found

Explanation

The in operator checks whether an element exists in a set.

Concepts Covered

  • Membership Operator

5. Python Program to Find the Union of Two Sets

Problem Statement

Write a Python program to find the union of two sets.

Python Solution

set1 = {1, 2, 3}
set2 = {3, 4, 5}

print(set1.union(set2))

Sample Output

{1, 2, 3, 4, 5}

Explanation

The union() method returns all unique elements from both sets.

Concepts Covered

  • union()

6. Python Program to Find the Intersection of Two Sets

Problem Statement

Write a Python program to find the common elements between two sets.

Python Solution

set1 = {10, 20, 30, 40}
set2 = {30, 40, 50, 60}

print(set1.intersection(set2))

Sample Output

{40, 30}

Explanation

The intersection() method returns only the common elements.

Concepts Covered

  • intersection()

7. Python Program to Find the Difference Between Two Sets

Problem Statement

Write a Python program to find the elements present in the first set but not in the second.

Python Solution

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

print(set1.difference(set2))

Sample Output

{1, 2}

Explanation

The difference() method returns elements that exist only in the first set.

Concepts Covered

  • difference()

8. Python Program to Remove Duplicate Values from a List

Problem Statement

Write a Python program to remove duplicate values from a list using a set.

Python Solution

numbers = [10, 20, 30, 20, 40, 10]

unique_numbers = list(set(numbers))

print(unique_numbers)

Sample Output

[40, 10, 20, 30]

Explanation

Converting a list into a set automatically removes duplicate values.

Concepts Covered

  • set()
  • Removing Duplicates

9. Python Program to Find Symmetric Difference Between Two Sets

Problem Statement

Write a Python program to find the elements that exist in either set but not in both.

Python Solution

set1 = {1, 2, 3}
set2 = {3, 4, 5}

print(set1.symmetric_difference(set2))

Sample Output

{1, 2, 4, 5}

Explanation

The symmetric_difference() method returns elements that are unique to each set.

Concepts Covered

  • symmetric_difference()

10. Python Program to Clear All Elements from a Set

Problem Statement

Write a Python program to remove all elements from a set.

Python Solution

languages = {"Python", "Java", "C++"}

languages.clear()

print(languages)

Sample Output

set()

Explanation

The clear() method removes every element from the set, leaving it empty.

Concepts Covered

  • clear()

11. Python Program to Find the Symmetric Difference Between Two Sets

Problem Statement

Write a Python program to find the symmetric difference between two sets. The symmetric difference contains elements that are present in either of the sets but not in both.

Python Solution

set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 60, 70, 80}

result = set1.symmetric_difference(set2)

print("Symmetric Difference:")
print(result)

Sample Output

Symmetric Difference:
{10, 20, 50, 60, 70, 80}

Explanation

The symmetric_difference() method returns elements that exist in only one of the two sets.

Concepts Covered

  • Set Operations
  • symmetric_difference()
  • Unique Elements

12. Python Program to Find the Cartesian Product of Two Sets

Problem Statement

Write a Python program to find the Cartesian product of two sets.

Python Solution

set1 = {1, 2, 3}
set2 = {"A", "B"}

cartesian = {(x, y) for x in set1 for y in set2}

print("Cartesian Product:")
print(cartesian)

Sample Output

Cartesian Product:
{(1, 'A'), (1, 'B'), (2, 'A'), (2, 'B'), (3, 'A'), (3, 'B')}

Explanation

The Cartesian product creates every possible pair by combining each element of the first set with every element of the second set.

Concepts Covered

  • Set Comprehension
  • Nested Loops
  • Cartesian Product

13. Python Program to Check Whether One Set is a Proper Subset of Another

Problem Statement

Write a Python program to determine whether one set is a proper subset of another.

Python Solution

set1 = {10, 20}
set2 = {10, 20, 30, 40}

if set1 < set2:
    print("set1 is a Proper Subset of set2")
else:
    print("set1 is NOT a Proper Subset")

Sample Output

set1 is a Proper Subset of set2

Explanation

The < operator checks whether every element of the first set exists in the second set and the sets are not equal.

Concepts Covered

  • Proper Subset
  • Comparison Operators
  • Set Relations

14. Python Program to Find Elements Appearing in Exactly One of Three Sets

Problem Statement

Write a Python program to display elements that appear in only one of three sets.

Python Solution

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
C = {4, 6, 7, 8}

result = (A - B - C) | (B - A - C) | (C - A - B)

print("Elements Present in Exactly One Set:")
print(result)

Sample Output

Elements Present in Exactly One Set:
{1, 2, 5, 7, 8}

Explanation

The program removes common elements and combines only those values that belong exclusively to one set.

Concepts Covered

  • Set Difference
  • Union
  • Multiple Set Operations

15. Python Program to Group Words by Their First Letter Using Sets

Problem Statement

Write a Python program to group words based on their first character using a dictionary of sets.

Python Solution

words = ["Apple", "Ant", "Banana", "Ball", "Cat", "Car"]

groups = {}

for word in words:
    first = word[0]

    if first not in groups:
        groups[first] = set()

    groups[first].add(word)

for key, value in groups.items():
    print(key, ":", value)

Sample Output

A : {'Apple', 'Ant'}
B : {'Ball', 'Banana'}
C : {'Car', 'Cat'}

Explanation

The program groups words by their starting letter while using sets to ensure that duplicate words are stored only once.

Concepts Covered

  • Sets
  • Dictionaries
  • add()
  • Data Grouping

16. Python Program to Find Duplicate Elements Across Multiple Sets

Problem Statement

Write a Python program to find all elements that appear in at least two out of three sets.

Python Solution

set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
set3 = {20, 40, 60, 80, 90}

duplicates = (set1 & set2) | (set2 & set3) | (set1 & set3)

print("Elements Appearing in At Least Two Sets:")
print(duplicates)

Sample Output

Elements Appearing in At Least Two Sets:
{20, 30, 40, 50, 60}

Explanation

The program finds common elements between every pair of sets using the intersection operator (&) and combines the results using the union operator (|).

Concepts Covered

  • Set Intersection
  • Set Union
  • Multiple Set Operations

17. Python Program to Find All Unique Characters from a Sentence

Problem Statement

Write a Python program to extract all unique alphabetic characters from a sentence and display them in sorted order.

Python Solution

sentence = input("Enter a sentence: ")

characters = {
    ch.lower()
    for ch in sentence
    if ch.isalpha()
}

print("Unique Characters:")
print(sorted(characters))

Sample Output

Enter a sentence: Python Programming

Unique Characters:
['a', 'g', 'h', 'i', 'm', 'n', 'o', 'p', 'r', 't', 'y']

Explanation

A set comprehension removes duplicate characters automatically, while sorted() arranges them alphabetically.

Concepts Covered

  • Set Comprehension
  • sorted()
  • String Processing

18. Python Program to Check Whether Two Lists Contain the Same Unique Elements

Problem Statement

Write a Python program to determine whether two lists contain the same unique values regardless of order and duplicate entries.

Python Solution

list1 = [10, 20, 20, 30, 40]
list2 = [40, 30, 20, 10, 10]

if set(list1) == set(list2):
    print("Both lists contain the same unique elements.")
else:
    print("The lists are different.")

Sample Output

Both lists contain the same unique elements.

Explanation

The lists are converted into sets, which automatically remove duplicate values before comparison.

Concepts Covered

  • List to Set Conversion
  • Equality Comparison
  • Duplicate Removal

19. Python Program to Find Missing Numbers from a Given Range Using Sets

Problem Statement

Write a Python program to find all missing numbers from a given range.

Python Solution

numbers = {1, 2, 4, 6, 7, 9}

full_range = set(range(1, 11))

missing = full_range - numbers

print("Missing Numbers:")
print(missing)

Sample Output

Missing Numbers:
{3, 5, 8, 10}

Explanation

The complete range is converted into a set, and the difference operation identifies the missing elements.

Concepts Covered

  • Set Difference
  • range()
  • Mathematical Sets

20. Python Program to Find the Power Set of a Given Set

Problem Statement

Write a Python program to generate the power set (all possible subsets) of a given set.

Python Solution

from itertools import combinations

numbers = {1, 2, 3}

power_set = []

data = list(numbers)

for r in range(len(data) + 1):
    for subset in combinations(data, r):
        power_set.append(set(subset))

print("Power Set:")

for subset in power_set:
    print(subset)

Sample Output

Power Set:
set()
{1}
{2}
{3}
{1, 2}
{1, 3}
{2, 3}
{1, 2, 3}

Explanation

The combinations() function from the itertools module generates every possible subset of the original set, including the empty set and the complete set.

Concepts Covered

  • Power Set
  • itertools.combinations
  • Nested Loops
  • Advanced Set Operations

21. Python Program to Find the Jaccard Similarity Between Two Sets

Problem Statement

Write a Python program to calculate the Jaccard Similarity between two sets. Jaccard Similarity is widely used in machine learning, recommendation systems, and text analysis.

Formula:

Jaccard Similarity = (Intersection of Sets) / (Union of Sets)

Python Solution

set1 = {"Python", "Java", "C++", "SQL"}
set2 = {"Python", "JavaScript", "SQL", "HTML"}

intersection = set1 & set2
union = set1 | set2

similarity = len(intersection) / len(union)

print("Intersection:", intersection)
print("Union:", union)
print("Jaccard Similarity:", round(similarity, 2))

Sample Output

Intersection: {'Python', 'SQL'}
Union: {'Python', 'Java', 'C++', 'JavaScript', 'HTML', 'SQL'}
Jaccard Similarity: 0.33

Explanation

The Jaccard Similarity measures how similar two sets are by comparing their common elements with the total unique elements.

Concepts Covered

  • Set Intersection
  • Set Union
  • len()
  • Real-world Machine Learning

22. Python Program to Find Mutual Friends Using Sets

Problem Statement

Write a Python program to find mutual friends between two users in a social networking application.

Python Solution

user1 = {"Rahul", "Amit", "Riya", "Neha", "Karan"}
user2 = {"Amit", "Riya", "Ankit", "Karan", "Priya"}

mutual = user1 & user2

print("Mutual Friends:")
print(mutual)

Sample Output

Mutual Friends:
{'Amit', 'Riya', 'Karan'}

Explanation

The intersection operator (&) returns friends common to both users.

Concepts Covered

  • Set Intersection
  • Social Network Analysis
  • Real-world Applications

23. Python Program to Recommend New Friends Using Set Difference

Problem Statement

Write a Python program to recommend friends who are present in one user’s friend list but not in another’s.

Python Solution

my_friends = {"Rahul", "Amit", "Riya"}
other_user = {"Rahul", "Amit", "Neha", "Priya", "Karan"}

recommendations = other_user - my_friends

print("Recommended Friends:")
print(recommendations)

Sample Output

Recommended Friends:
{'Neha', 'Priya', 'Karan'}

Explanation

The set difference operator (-) returns only those friends that are not already in the user’s friend list.

Concepts Covered

  • Set Difference
  • Recommendation Systems
  • Real-world Projects

24. Python Program to Detect Duplicate Email Addresses

Problem Statement

Write a Python program to detect duplicate email addresses from a list using sets.

Python Solution

emails = [
    "abc@gmail.com",
    "xyz@gmail.com",
    "abc@gmail.com",
    "test@gmail.com",
    "xyz@gmail.com"
]

duplicates = set()
seen = set()

for email in emails:
    if email in seen:
        duplicates.add(email)
    else:
        seen.add(email)

print("Duplicate Emails:")
print(duplicates)

Sample Output

Duplicate Emails:
{'abc@gmail.com', 'xyz@gmail.com'}

Explanation

One set stores previously seen emails, while another stores duplicates, ensuring each duplicate appears only once.

Concepts Covered

  • Sets
  • Duplicate Detection
  • Data Cleaning

25. Python Program to Find the Most Common Skills Among Employees

Problem Statement

Write a Python program to find skills that are common to all employees.

Python Solution

employee1 = {"Python", "SQL", "Excel", "Power BI"}
employee2 = {"Python", "SQL", "Tableau", "Power BI"}
employee3 = {"Python", "SQL", "Power BI", "Machine Learning"}

common_skills = employee1 & employee2 & employee3

print("Common Skills:")
print(common_skills)

Sample Output

Common Skills:
{'Python', 'SQL', 'Power BI'}

Explanation

The intersection of multiple sets returns only the skills that every employee possesses.

Concepts Covered

  • Multiple Set Intersection
  • HR Analytics
  • Data Analysis
  • Real-world Business Problem

Frequently Asked Questions (FAQs)

1. What is a set in Python?

A set is an unordered, mutable collection of unique elements. Sets automatically remove duplicate values and are created using curly braces {} or the set() function.


2. Why are duplicate elements not allowed in a set?

Sets are designed to store only unique values. When duplicate elements are added, Python automatically ignores the repeated values.


3. What are the most commonly used set operations in Python?

The most common set operations are:

  • Union (|)
  • Intersection (&)
  • Difference (-)
  • Symmetric Difference (^)
  • Subset (<=)
  • Superset (>=)

These operations are useful for comparing and manipulating collections of unique data.


4. What is the difference between remove() and discard() in sets?

  • remove() raises a KeyError if the element does not exist.
  • discard() removes the element if it exists but does nothing if it is missing.

Example:

numbers = {10, 20, 30}

numbers.discard(40)   # No Error
# numbers.remove(40)  # Raises KeyError

5. Can a set contain another set?

No. Since sets are mutable, they cannot be stored inside another set. However, you can use a frozenset, which is immutable.

Example:

set1 = {1, 2}
set2 = {frozenset(set1)}

print(set2)

6. What is a frozenset in Python?

A frozenset is an immutable version of a set. Once created, its elements cannot be added or removed. It is commonly used as a dictionary key or as an element inside another set.


7. Where are Python sets used in real-world applications?

Sets are widely used in:

  • Data Cleaning
  • Removing Duplicate Records
  • Search Engines
  • Recommendation Systems
  • Machine Learning
  • Social Network Analysis
  • Database Operations
  • Cybersecurity and Access Control

8. Why are sets faster than lists for searching?

Sets use hash tables, allowing average-case lookup, insertion, and deletion in O(1) time, whereas lists require O(n) time for searching.


9. What is the time complexity of common set operations?

OperationAverage Time Complexity
Add ElementO(1)
Remove ElementO(1)
Membership Test (in)O(1)
UnionO(len(set1) + len(set2))
IntersectionO(min(len(set1), len(set2)))
DifferenceO(len(set1))

10. Why are sets important for Python interviews?

Set-based questions are common in Python interviews because they test your understanding of unique data handling, hashing, algorithm optimization, and real-world problem-solving. Mastering sets helps you write faster, cleaner, and more efficient Python programs for data science, software development, automation, and competitive programming.

Chapter Summary

After completing this chapter, you have learned:

  • Creating sets
  • add()
  • remove()
  • Membership testing
  • union()
  • intersection()
  • difference()
  • symmetric_difference()
  • clear()
  • Removing duplicate values using sets

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top