Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ“š Python Set: Practice Assignments

Python Set Practice Assignments

Comprehensive practice covering set creation, methods, iteration, unpacking, comprehension, and more.

Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers to make programming easy through practical examples and clear explanations.
šŸ“‘ On this page:
  • About
  • Set Creation
  • Set Methods
  • Iteration
  • Set Comprehension
  • Advanced
  • Try It
Share:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link

About These Assignments

This page contains 30+ unique practice assignments covering all set concepts in Python. Unlike the topic-specific pages, these problems are designed to test your ability to choose the right set technique for each situation and combine set operations effectively.

🟢 Beginner 🟠 Intermediate šŸ”“ Advanced
šŸŽÆ Unique Challenge: Each problem is designed to be different from the topic-specific assignments. You'll need to decide which set technique (methods, comprehension, unpacking, etc.) is most appropriate for each scenario.

šŸ’” Tip: Try each problem yourself first. Click "Show Solution" only after attempting.

1. Set Creation Challenges 4 Questions

šŸŽÆ Focus: Create sets using different techniques.
Beginner Q1: Create Set from List
Create a set from a list containing duplicate elements (remove duplicates).
šŸ’” Solution:
numbers = [1, 2, 3, 2, 4, 1, 5, 3, 6]
unique_set = set(numbers)
print(unique_set) # {1, 2, 3, 4, 5, 6}
šŸ“– Explanation: set() constructor removes duplicates automatically.
Beginner Q2: Set of Characters
Create a set of unique characters from a string.
šŸ’” Solution:
text = "hello world"
char_set = set(text)
print(char_set) # {'h', 'e', 'l', 'o', ' ', 'w', 'r', 'd'}
šŸ“– Explanation: Strings are iterable, set() creates unique characters.
Intermediate Q3: Set of Tuples
Create a set containing tuples of (name, age).
šŸ’” Solution:
data = {("Alice", 25), ("Bob", 30), ("Charlie", 35)}
print(data) # {('Alice', 25), ('Bob', 30), ('Charlie', 35)}
šŸ“– Explanation: Sets can contain tuples (hashable) as elements.
Advanced Q4: Set from Range with Condition
Create a set of even numbers from 1 to 20 using set comprehension.
šŸ’” Solution:
evens = {x for x in range(1, 21) if x % 2 == 0}
print(evens) # {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
šŸ“– Explanation: Set comprehension with condition.

2. Set Methods Challenges 6 Questions

šŸŽÆ Focus: Use built-in set methods effectively.
Beginner Q5: Add and Remove
Add an element to a set, then remove it using remove() and discard().
šŸ’” Solution:
s = {1, 2, 3, 4, 5}
s.add(6)
print(s) # {1, 2, 3, 4, 5, 6}
s.remove(3)
print(s) # {1, 2, 4, 5, 6}
s.discard(10) # No error if element not found
print(s) # {1, 2, 4, 5, 6}
šŸ“– Explanation: add() inserts, remove() raises KeyError if missing, discard() doesn't.
Beginner Q6: Pop and Clear
Remove and return an arbitrary element using pop(), then clear the set.
šŸ’” Solution:
s = {10, 20, 30, 40, 50}
removed = s.pop()
print(f"Removed: {removed}, Set: {s}")
s.clear()
print(f"After clear: {s}")
šŸ“– Explanation: pop() removes arbitrary element, clear() empties the set.
Intermediate Q7: Union and Intersection
Find the union and intersection of two sets.
šŸ’” Solution:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
union = A.union(B)
intersection = A.intersection(B)
print(f"Union: {union}")
print(f"Intersection: {intersection}")
šŸ“– Explanation: union() combines sets, intersection() finds common elements.
Intermediate Q8: Difference and Symmetric Difference
Find the difference and symmetric difference of two sets.
šŸ’” Solution:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
diff = A.difference(B)
sym_diff = A.symmetric_difference(B)
print(f"Difference (A - B): {diff}")
print(f"Symmetric Difference: {sym_diff}")
šŸ“– Explanation: difference() removes elements in B, symmetric_difference() removes common elements.
Intermediate Q9: Subset and Superset
Check if one set is a subset or superset of another.
šŸ’” Solution:
A = {1, 2, 3, 4, 5}
B = {1, 2, 3}
print(f"B is subset of A: {B.issubset(A)}") # True
print(f"A is superset of B: {A.issuperset(B)}") # True
šŸ“– Explanation: issubset() checks if all elements are in other set, issuperset() checks opposite.
Advanced Q10: Update and Difference Update
Update a set with elements from another set, then remove elements using difference_update.
šŸ’” Solution:
A = {1, 2, 3}
B = {3, 4, 5}
A.update(B)
print(f"After update: {A}") # {1, 2, 3, 4, 5}
A.difference_update({2, 4})
print(f"After difference_update: {A}") # {1, 3, 5}
šŸ“– Explanation: update() adds elements, difference_update() removes elements in specified set.

3. Iteration Challenges 3 Questions

šŸŽÆ Focus: Iterate over sets effectively.
Beginner Q11: Simple Iteration
Iterate over a set and print each element.
šŸ’” Solution:
colors = {"red", "green", "blue", "yellow"}
for color in colors:
print(color)
šŸ“– Explanation: Sets are iterable, but order is not guaranteed.
Intermediate Q12: Iterate and Process
Iterate over a set of numbers and create a list of their squares.
šŸ’” Solution:
nums = {1, 2, 3, 4, 5}
squares = []
for num in nums:
squares.append(num ** 2)
print(squares) # [1, 4, 9, 16, 25]
šŸ“– Explanation: Iterates through set and builds a list.
Advanced Q13: Set of Sets Iteration
Iterate over a frozenset (hashable set) containing tuples.
šŸ’” Solution:
data = {frozenset({1, 2}), frozenset({3, 4}), frozenset({5, 6})}
for fs in data:
for item in fs:
print(item, end=' ')
print()
šŸ“– Explanation: Frozensets can be elements of sets, enabling nested iteration.

4. Set Comprehension Challenges 4 Questions

šŸŽÆ Focus: Use set comprehension for concise set creation.
Beginner Q14: Squares with Comprehension
Create a set of squares of numbers 1-10 using set comprehension.
šŸ’” Solution:
squares = {x**2 for x in range(1, 11)}
print(squares) # {1, 4, 9, 16, 25, 36, 49, 64, 81, 100}
šŸ“– Explanation: {expression for item in iterable}.
Beginner Q15: Filter with Comprehension
Create a set of numbers divisible by 3 from 1 to 30.
šŸ’” Solution:
multiples = {x for x in range(1, 31) if x % 3 == 0}
print(multiples) # {3, 6, 9, 12, 15, 18, 21, 24, 27, 30}
šŸ“– Explanation: With condition filter.
Intermediate Q16: Nested Comprehension
Create a set of all possible sums from two lists using nested comprehension.
šŸ’” Solution:
A = [1, 2, 3]
B = [4, 5, 6]
sums = {a + b for a in A for b in B}
print(sums) # {5, 6, 7, 8, 9}
šŸ“– Explanation: Nested comprehension with two for clauses.
Advanced Q17: Conditional with else
Create a set that categorizes numbers as "even" or "odd".
šŸ’” Solution:
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = {f"{x} is even" if x % 2 == 0 else f"{x} is odd" for x in nums}
print(result)
šŸ“– Explanation: Ternary operator inside comprehension.

5. Advanced Set Challenges 5 Questions

šŸŽÆ Focus: Combine multiple set techniques.
Advanced Q18: Find Common Elements
Find common elements between three sets.
šŸ’” Solution:
A = {1, 2, 3, 4, 5}
B = {3, 4, 5, 6, 7}
C = {5, 6, 7, 8, 9}
common = A.intersection(B, C)
print(f"Common elements: {common}") # {5}
šŸ“– Explanation: intersection() can take multiple arguments.
Advanced Q19: Remove Duplicates from List
Remove duplicates from a list while preserving the original order using set.
šŸ’” Solution:
def unique_preserve_order(lst):
seen = set()
result = []
for item in lst:
if item not in seen:
seen.add(item)
result.append(item)
return result
data = [1, 2, 3, 2, 4, 1, 5, 3, 6]
print(unique_preserve_order(data)) # [1, 2, 3, 4, 5, 6]
šŸ“– Explanation: Uses set for O(1) membership check while preserving order.
Advanced Q20: Set of Dictionaries
Create a set of dictionaries (using frozenset of items).
šŸ’” Solution:
dict1 = {"name": "Alice", "age": 25}
dict2 = {"name": "Bob", "age": 30}
# Convert dictionaries to frozenset of items for hashing
set_of_dicts = {frozenset(dict1.items()), frozenset(dict2.items())}
for fs in set_of_dicts:
print(dict(fs))
šŸ“– Explanation: Frozenset of items makes dictionaries hashable for sets.
Advanced Q21: Set Operations with Lists
Find elements present in first list but not in second, and vice versa.
šŸ’” Solution:
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
set1 = set(list1)
set2 = set(list2)
only_in_1 = set1 - set2
only_in_2 = set2 - set1
print(f"Only in list1: {only_in_1}")
print(f"Only in list2: {only_in_2}")
šŸ“– Explanation: Set difference to find unique elements in each list.
Advanced Q22: Partition Set
Partition a set into two sets: one with even numbers and one with odd numbers.
šŸ’” Solution:
nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
evens = {x for x in nums if x % 2 == 0}
odds = nums - evens
print(f"Evens: {evens}")
print(f"Odds: {odds}")
šŸ“– Explanation: Set comprehension and set difference for partitioning.

Try It Yourself!

Use the interactive editor below to test your solutions or write your own set code.

Loading Pyodide... 0%
Python Code Editor
========================================
SET PRACTICE
========================================
Unique numbers: {1, 2, 3, 4, 5, 6}
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Squares: {1, 4, 9, 16, 25}
Colors:
- red
- green
- blue

āœ… Write your set solutions here!

šŸ“š Related Tutorials

šŸ“¦ Set in Python

Learn about sets in Python

šŸ”§ Set Methods

Explore built-in set methods

⚔ Set Comprehension

Master set comprehension

šŸ“– Related Tutorials
  • Access Set Elements
  • Iterate Set
  • Pack/Unpack Set
  • List vs Set
Previous: Set Comprehension Next: Dictionary in Python →