Sets: Practice Questions
100 questions. Try each one yourself before checking the answer.
Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.
Create a set called colours holding "red", "green" and "blue", then print it and its type.
Create a set from the values 1, 2, 2, 3, 3, 3 and print it along with its length. Explain the result in a comment.
Create an empty set and print its type. Then show what {} actually creates.
Given numbers = [3, 7, 3, 2, 7, 8, 3], build a set from it and print the unique values in sorted order, plus how many duplicates were removed.
Build a set of the distinct characters in "mississippi" and print them sorted, with the count.
Using fruits = {"apple", "banana", "cherry"}, print whether "banana" is in it and whether "mango" is not.
Start with an empty set, add "red", "green" and "blue" one at a time with .add(), then try adding "red" again and print the result.
Given colours = {"red", "green"}, add several values at once from a list using .update(), then print the set sorted.
Using colours = {"red", "green", "blue"}, remove "green" with .remove() and print the result.
Show the difference between .remove() and .discard() when the value is not in the set.
Use .pop() to take an item out of a set and print both the item and what is left. Explain in a comment which item you get.
Empty a set with .clear() and print it with its length.
Loop over {"red", "green", "blue"} printing each colour, then do it again in a predictable order.
Show that a set does not support indexing or slicing, and give the correct way to get a specific item out.
Given a = {1, 2, 3} and b = {3, 4, 5}, print everything that is in either set, using the | operator.
Using the same two sets, print only the values found in both, using &.
Print the values that are in a but not in b, then the values in b but not in a.
Print the values that are in one set or the other but not both, using ^.
Repeat the four operations from Q15–Q18 using the method names instead of the operators.
Given small = {1, 2} and big = {1, 2, 3, 4}, print whether every item of small is inside big, both with <= and with .issubset().
Using the same sets, print whether big contains everything in small, using >= and .issuperset().
Print whether {1, 2} and {3, 4} share nothing at all, and whether {1, 2} and {2, 3} do.
Show that two sets are equal when they hold the same values, no matter what order they were written in or how many duplicates were typed.
Given marks = {78, 92, 65, 88, 71}, print the total, highest, lowest and average.
Put the same values into a list and a set, then print both with their lengths and explain the two differences you can see.
Build a set of the squares of 1 to 10 using a loop and .add(), then print it sorted.
Remove duplicates from ["b", "a", "c", "a", "b", "d"] while keeping the original order, using a set to remember what has been seen.
Given a = {1, 2, 3}, fold {3, 4, 5} into it in place using |=, then show .update() does the same thing.
Given a = {1, 2, 3, 4}, cut it down in place to only the values it shares with {3, 4, 5}, using &=.
Given a = {1, 2, 3, 4, 5}, remove several values in one go using -=, then do the same with .difference_update().
Given a = {1, 2, 3}, use ^= to keep only the values that are in exactly one of a and {3, 4, 5}.
Given three sets of course enrolments, print everyone enrolled in any course, and everyone enrolled in all three.
Show that .union() accepts a plain list while | does not, and explain when each form is the better choice.
Ask for a sentence and print how many distinct words it contains, and the sorted list of them, ignoring case.
Given two sentences, print the words they share, the words unique to each, and how many words are common.
Given two words, print the letters that appear in the first but not the second, and vice versa.
Write vowels_in(word) that returns the set of vowels a word actually contains, then use it on three words.
Write has_duplicates(items) that returns True when a list contains any repeated value, using a set and no loops.
Now find which values are duplicated in [3, 7, 3, 2, 7, 8, 3], returning them as a set.
Build a set of (name, mark) tuples, including a repeated record, and show the duplicate is dropped.
Show that a list cannot be put into a set but a tuple can, and explain why in a comment.
Create a frozenset, show it supports all the reading operations, and show it rejects .add().
Show that a set cannot contain another set, but can contain a frozenset. Build a set of two frozensets.
Build a set from a range(), then print the multiples of 3 up to 30 that it contains, using a set operation.
Show the difference between a subset (<=) and a proper subset (<) using two identical sets.
Prove that the symmetric difference equals the union with the intersection removed, by computing both ways and comparing.
Show that b = a makes an alias of a set while .copy() makes a real copy, using .add() to prove it.
Given a list of all students and a set of those who have paid, print who still owes, sorted.
Write compare(a, b) that takes two lists and returns the shared, only-in-a and only-in-b values as three sets, unpacked by the caller.
Given a list of tags with duplicates, print the total count, the distinct count, and the distinct tags in alphabetical order — then explain why you cannot ask for "the third tag added".
Two courses have enrolment lists. Print who takes both, who takes only Python, who takes only Maths, and the total number of distinct students.
Given a set of registered students and a list of those who actually attended, report who never turned up and who attended without registering.
Given two people's friend lists, print their mutual friends, the friends unique to each, and whether they share nobody at all.
Given a log of page visits by user, report the number of visits, the number of unique visitors, and which users visited more than once.
Given a small dictionary of known words as a set, check a sentence and report any words that are not recognised.
A task needs certain permissions. Given what a user has been granted, report whether they may proceed and exactly what is missing.
Write is_pangram(sentence) that returns True when a sentence uses every letter of the alphabet, and report which letters are missing when it does not.
Write all_unique(text) that returns True when no character repeats, ignoring case and spaces, and test it on three strings.
Compare yesterday's and today's stock lists, reporting which items were added, which were removed, and which stayed.
Given the winning lottery numbers and a player's ticket, report how many matched, which ones, and the prize tier.
Given a job's required skills and a candidate's skills, print the match percentage, the gaps, and the extra skills they bring.
Given survey answers from several people, print how many distinct answers were given and which answers only one person chose.
Merge a subscribe list and an unsubscribe list into a final mailing list, then report the size change.
Two restaurant branches have menus. Print the shared dishes, the branch-exclusive dishes, and whether either menu fully covers the other.
Given a set of blocked words, check a message and report whether it may be posted, listing any blocked words used.
Given all seat numbers in a row and the seats already booked, print the available seats in order and the occupancy percentage.
Given a list of (name, email) records containing exact duplicates, remove the duplicates with a set and print the cleaned records sorted.
Two clubs have member lists. Print the students who belong to exactly one club, and separately name which club each of them is in.
Two library members have borrowing histories. Print every distinct book either has read, the ones both read, and how many books each read that the other did not.
Write common_to_all(lists) that takes a list of lists and returns the values present in every one of them, coping with an empty input.
This is meant to collect unique tags but crashes on the first .add(). Find and fix the bug.
tags = {}
tags.add("python")
print(tags)Explain why this set ends up with far fewer items than values written into it.
values = {1, 1.0, True, 0, False, "1"}
print(values)
print(len(values))This code is meant to always print the same report but the lines come out in different orders. Explain why, and fix it.
scores = {88, 74, 91, 65}
for score in scores:
print(score)Write remove_all(target, values) that removes every value in values from the set target, without crashing on ones that are not there. Show two ways.
This raises RuntimeError: Set changed size during iteration. Explain why and fix it two ways.
numbers = {1, 2, 3, 4, 5, 6}
for n in numbers:
if n % 2 == 0:
numbers.discard(n)
print(numbers)This is meant to serve customers in the order they arrived, but serves them in a jumble. Explain the mistake and give the right tool.
queue = {"Asha", "Raj", "Meera"}
while len(queue) > 0:
print(f"Serving {queue.pop()}")Explain why these two lines produce completely different sets, and show how to build each one deliberately.
a = set("hello")
b = {"hello"}This should end up holding the shared values but prints the original set unchanged. Find and fix the bug.
a = {1, 2, 3, 4}
b = {3, 4, 5}
a & b
print(a)This anagram checker says "aab" and "abb" are anagrams. Explain why sets are the wrong tool here and give a correct version.
def is_anagram(a, b):
return set(a) == set(b)
print(is_anagram("listen", "silent"))
print(is_anagram("aab", "abb"))Show that float arithmetic can make a membership test fail even when the value looks right, and give a reliable alternative.
Show why membership testing is so much cheaper on a set than a list, by counting the steps a list search actually takes.
Compare the work done by two ways of removing duplicates: the Topic 8 loop with not in unique, and a set. Count the comparisons each one makes.
Build a set of unique coordinates from a list of points, showing that tuples work and explaining what to do if the points arrive as lists.
Given a list of (a, b) pairings where ("Asha", "Raj") and ("Raj", "Asha") mean the same partnership, count the distinct partnerships using frozensets.
Show that a set of mixed types can be built but not sorted, and give two ways to print it predictably anyway.
Build a Course Enrolment Analyser. Hold three course rosters as sets and offer a menu to show any course, students in both of two courses, students in all three, students in exactly one, and the full distinct roll.
Build a Data Cleaner. Read values until the user types done, then report the total entered, the unique values, which ones were repeated, which appeared exactly once, and the cleaned list in both sorted and original order.
Build a Spell Checker. Hold a small dictionary as a set, check a sentence, report unknown words, and suggest a correction for each unknown word by finding known words that share most of their letters.
Build an Interest Matcher. Store several people's interests as sets, then print a table of how well every pair matches and name the best-matched pair.
Build an Access Auditor. Given the permissions each role requires and what each user has been granted, report per user whether they may work, what is missing, and what they hold unnecessarily.
Build a Lottery Checker. Read a ticket of six numbers from the user, validate that they are in range and not repeated, then compare against the winning set and report the result.
Build a Visitor Report from a log of (page, user) tuples: unique visitors overall, unique visitors per page, pages seen by everyone, and users who saw only one page.
Build a Vocabulary Comparer for two texts: distinct word counts, shared vocabulary, words unique to each, and a richness score for both.
Build a Seat Booking System. Keep all seats and booked seats as sets, and offer book, cancel, show available, and a summary — refusing double bookings and rejecting invalid seat numbers.
Build a Skill Gap Report. Compare several candidates against one job's required and desirable skills, ranking them by how well they match.
Compare lists, tuples and sets across every dimension that matters — order, duplicates, mutability, what can go inside, and how fast membership is. Demonstrate each claim.
Explain why a set can only hold hashable values. Show what breaks when a value changes after being stored, using a tuple containing a list as the example.
Explain in your own words how a set achieves near-instant membership testing, and what that costs. Demonstrate the trade-off.
Give three concrete situations where reaching for a set would be a mistake, and show the right tool for each.
Capstone. Build a Set Toolkit Report. Read two groups of values, then print one report showing each group's distinct members, the union, intersection, both differences, the symmetric difference, subset and disjoint checks, the overlap percentage, and which values were duplicated within each group.
Still stuck on something?
Book a free 1-on-1 session and we'll work through it together.
Book a Free Session