Explore programming tutorials, exercises, quizzes, and solutions!
Python Sets Exercises
1/20
You're exploring different data structures in Python and come across sets. Sets are unordered collections that do not allow duplicate values. They are especially useful when you need to store a group of unique items or perform operations like unions and intersections.
What does this example illustrate about how Python handles sets?
This example shows that Python sets automatically eliminate duplicate values. When "red" appears twice in the set declaration, Python keeps only one instance of it.
Sets are unordered, so when printed, the elements may not appear in the order you wrote them. The output will look something like:
{'green', 'red', 'blue'}
This behavior makes sets ideal for tasks where uniqueness is important, such as removing duplicates from a collection or comparing distinct elements between datasets. Sets in Python are defined using curly braces {} or the set() constructor and support powerful operations like union, intersection, and difference.
Which of the following will create an empty set?
The correct way to create an empty set in Python is set(). Using {} creates an empty dictionary, not a set.
What will be the output of the following code?
s = {1, 2, 3, 2, 1}
print(len(s))
Although the set is defined with duplicate values, sets store only unique elements. So s becomes {1, 2, 3}, and its length is 3.
Which method is used to add an item to a set in Python?
To add an item to a set, you use the add() method. Other methods like append() and extend() are used with lists, not sets.
Which of the following statements about sets is False?
Sets cannot contain duplicate values. If duplicates are added during set creation, they are automatically removed. All other statements are true about sets.
What will be the output of the following code?
s = {1, 2, 3, 4}
s.remove(2)
print(s)
The remove() method removes an element from the set. In this case, 2 is removed from the set {1, 2, 3, 4}, resulting in {1, 3, 4}.
What will the following code output?
s = {1, 2, 3, 4}
print(3 in s)
The expression 3 in s checks if the value 3 exists in the set s. Since 3 is present in the set, the result is True.
What will the following code output?
s = {1, 2, 3, 4, 5}
s.discard(6)
print(s)
The discard() method removes an element from the set, but if the element does not exist, it does nothing. In this case, since 6 is not in the set, the set remains unchanged: {1, 2, 3, 4, 5}.
What will the following code output?
s1 = {1, 2, 3}
s2 = {3, 4, 5}
print(s1 & s2)
The & operator finds the intersection of two sets, which means it returns the elements that are common in both sets. In this case, the intersection of s1 and s2 is {3}.
Which of the following methods can be used to remove all elements from a set?
The clear() method removes all elements from a set, making it an empty set. Other options like delete(), remove_all(), and reset() are not valid methods for sets.
What will be the output of the following code?
s = {1, 2, 3, 4}
s.add([5, 6])
print(s)
The add() method in sets only accepts hashable (immutable) elements. A list [5, 6] is mutable, so it cannot be added to a set. This will raise a TypeError.
Which of the following statements is true about sets?
Sets are unordered collections, which means they do not support indexing or slicing. They also cannot contain mutable items like lists or dictionaries. Sets only store unique elements.
What will the following code output?
s1 = {1, 2, 3}
s2 = {3, 4, 5}
print(s1 | s2)
The | operator performs a union between two sets, meaning it returns all elements from both sets, eliminating duplicates. So, the result of s1 | s2 is {1, 2, 3, 4, 5}.
The symmetric_difference() method returns a set of elements that are in either of the sets, but not in both. So, it will return {1, 2, 5, 6} as 3 and 4 are common in both sets.
What will the following code output?
s = {1, 2, 3, 4}
s.discard(2)
s.remove(3)
print(s)
The discard() method removes an element if it exists in the set. Since 2 exists in the set, it is removed. The remove() method removes an element, but if it does not exist, it raises an error. Since 3 is present, it is removed. Therefore, the resulting set is {1, 4}.
What will be the output of the following code?
s = {1, 2, 3, 4}
s.add("hello")
s.add((5, 6))
print(s)
The add() method adds elements to the set. Both a string 'hello' and a tuple (5, 6) can be added to the set because they are hashable. Therefore, the resulting set will be {1, 2, 3, 4, 'hello', (5, 6)}.
The update() method adds elements from an iterable or another set to the set. Here, both a list [5, 6] and a set {7, 8} are added. Sets automatically eliminate duplicates, so the result is {1, 2, 3, 4, 5, 6, 7, 8}.
What will be the output of the following code?
s = {1, 2, 3, 4}
t = {3, 4, 5, 6}
print(s != t)
The != operator checks if two sets are not equal. In this case, the sets s and t are different because they contain different elements, so the result is True.
What will be the output of the following code?
s = {1, 2, 3, 4, 5}
print(s.pop())
The pop() method removes and returns a random element from the set. Since sets are unordered, the element that is removed is not predictable. It could be any element from the set.
What will be the output of the following code?
s = {1, 2, 3, 4, 5}
t = {2, 3, 6}
print(s - t)
The - operator performs a difference operation between two sets, returning a set of elements that are in the first set but not in the second set. Here, s - t results in {1, 4, 5} because 2 and 3 are in both sets.
Practicing Python Sets? Don’t forget to test yourself later in
our
Python Quiz.
About This Exercise: Python – Sets
Welcome to the Python Sets exercises — a targeted collection designed to help you master sets, a powerful and unique data structure in Python. Sets are widely used for storing unordered collections of unique elements, making them essential when you need fast membership tests, eliminate duplicates, or perform mathematical set operations like unions and intersections.
This set of exercises will guide you through the fundamentals of creating, accessing, and manipulating sets in Python. You’ll learn how to add and remove elements, use set methods and operators, and understand important properties like immutability of set elements and how sets differ from lists and tuples.
As you work through these exercises, you’ll explore practical scenarios such as removing duplicates from data, comparing datasets, and efficiently checking membership. These skills are invaluable not only in academic projects but also in real-world applications like data analysis, web development, and algorithm optimization.
Beyond the basics, the exercises also cover more advanced topics like set comprehension, frozensets (immutable sets), and how to combine sets with other Python data structures. Understanding sets deeply will improve your ability to write clean, efficient, and Pythonic code that handles complex data operations with ease.
Whether you are preparing for coding interviews, enhancing your academic knowledge, or developing professional Python applications, mastering sets will add a valuable tool to your programming toolkit. Our exercises are structured to suit all levels, from beginners getting familiar with set syntax to more experienced developers tackling tricky set problems.
We also encourage you to explore related topics like lists, dictionaries, tuples, and control flow to see how sets integrate within the larger Python ecosystem. Complement your practice with our Python MCQs and quizzes to test your understanding and retention of key concepts.
Start working through the Python Sets exercises today and unlock the power of this versatile data structure. With regular practice, you’ll gain confidence in handling unique collections and set operations, making your Python programs faster, smarter, and more efficient.