Set Exercises (Python Programming)
Learn Set Exercises (Python Programming) step by step with clear examples and exercises.
Title: Python Set Exercises - Practical Deep Dive into Python Sets
Why This Matters
Python sets are a powerful tool for handling unique collections of data, and mastering them can make your code more efficient and readable. In this lesson, we'll look closely at Python sets by exploring their creation, manipulation, and use in real-world scenarios. You'll learn practical techniques to solve complex problems, identify common mistakes, and gain interview-ready one-liners for your programming toolkit.
Prerequisites
To get the most out of this lesson, you should have a good understanding of Python basics, including variables, functions, loops, and control structures. Familiarity with data structures like lists and dictionaries will also be helpful as we compare and contrast sets with other collections.
Core Concept
What are Python Sets?
A set is a collection of unique elements that cannot be ordered or indexed like lists, but can be iterated through. In Python, sets are implemented as built-in data structures, and they offer several advantages over lists:
- Unique elements only: Unlike lists, sets automatically remove any duplicate values when added.
- Faster membership testing: Checking if an element is in a set is faster than checking the same for a list because sets use hashing to store their data.
- Efficient mathematical operations: Sets provide methods for performing common set operations like union, intersection, difference, and symmetric difference.
- No defined order: The elements in a set have no specific ordering, making it easier to focus on the unique values themselves rather than their positions.
Creating Python Sets
To create a set, you can use curly braces {}, a set constructor set(), or the set() function with iterable elements. Here are examples of each method:
Using curly braces
my_set1 = {1, 2, 3, 4}
Using the set constructor
my_set2 = set([5, 6, 7, 8])
Using the set() function
my_set3 = set((9, 10, 11, 12))
### Set Operations
Python sets offer several methods for performing common set operations:
- `union(other)`: Returns a new set containing all elements from both the current set and the specified other set.
- `intersection(other)`: Returns a new set containing only the elements that are common to both the current set and the specified other set.
- `difference(other)`: Returns a new set containing all elements from the current set except those that are also in the specified other set.
- `symmetric_difference(other)`: Returns a new set containing only the elements that are unique to either the current set or the specified other set, but not both.
- `issubset(other)`: Returns `True` if all elements of the current set are also in the specified other set; otherwise, returns `False`.
- `issuperset(other)`: Returns `True` if all elements of the specified other set are also in the current set; otherwise, returns `False`.
### Set Comprehensions
Like list comprehensions, you can create sets using a compact syntax called set comprehensions. Here's an example:
Creating a set containing all even numbers between 1 and 20
even_numbers = {num for num in range(1, 21) if num % 2 == 0}
Worked Example
Let's say we have two sets representing the students who are enrolled in two different courses: courseA and courseB. We want to find out how many students are enrolled in both courses, and how many are only enrolled in one course.
Sample data
courseA = {"Alice", "Bob", "Charlie", "Dave", "Eve"}
courseB = {"Alice", "Bob", "Carol", "Dave", "Frank"}
Find students enrolled in both courses
both_courses = courseA.intersection(courseB)
print("Students enrolled in both courses:", both_courses)
Find students enrolled only in courseA
courseA_only = courseA.difference(courseB)
print("Students enrolled only in courseA:", courseA_only)
Find students enrolled only in courseB
courseB_only = courseB.difference(courseA)
print("Students enrolled only in courseB:", courseB_only)
Common Mistakes
- Treating a set like a list: Sets are not ordered, and you cannot access elements by index. Instead, iterate through the set using a loop or a for-comprehension.
- Adding duplicate values: Since sets automatically remove duplicates, adding duplicate values will have no effect on the set.
- Using mutable objects as set members: If you add a mutable object (like a list) to a set, any changes made to that object outside of the set will affect its presence in the set. To avoid this issue, convert mutable objects to tuples or immutable sets before adding them to your main set.
- Not understanding the difference between sets and dictionaries: While both sets and dictionaries store unique values, they have different use cases. Dictionaries are key-value pairs, while sets are unordered collections of unique elements.
- Using
inornot inwith a set as the left operand: Theinandnot inoperators expect iterable objects on their right side, so you'll need to convert your set to a list (usinglist()) before using these operators.
Practice Questions
- Write a function that takes two lists as arguments and returns a new set containing all common elements in both lists.
- Given the following sets, find the union, intersection, difference, and symmetric difference between
{"apple", "banana", "cherry"}and{"orange", "grape", "berry"}. - Write a set comprehension that generates all odd numbers between 1 and 50.
- Given the following sets, find out if
courseCis a subset ofcourseA.
courseA = {"Alice", "Bob", "Charlie", "Dave", "Eve"}
courseB = {"Carol", "Dave", "Frank", "George", "Hannah"}
courseC = {"Alice", "Bob", "Charlie", "Dave"}
FAQ
- Why are sets faster for membership testing than lists? Sets use hashing to store their data, which allows for constant-time O(1) lookups when checking if an element is present in the set. In contrast, lists require linear time O(n) to search for an element.
- Can I convert a list to a set using a single line of code? Yes! You can use the
set()function or set constructor to create a new set from a list:
my_list = [1, 2, 3, 4]
my_set = set(my_list)
- What happens if I add an empty set to another set? Adding an empty set (
set()) to another set will return the original set with no changes. If you add a non-empty set, Python will concatenate the sets by combining their elements. - Can I sort the elements in a set? No, sets do not maintain any specific order for their elements. If you need to sort a set, convert it to a list first and then sort the list before converting it back to a set if needed.