Python · Python Collections

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.

Q1Creating SetsEasy

Create a set called colours holding "red", "green" and "blue", then print it and its type.

Q2UniquenessEasyMust Do

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.

Q3Creating SetsEasyMust Do

Create an empty set and print its type. Then show what {} actually creates.

Q4ConversionEasyMust Do

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.

Q5ConversionEasy

Build a set of the distinct characters in "mississippi" and print them sorted, with the count.

Q6MembershipEasyMust Do

Using fruits = {"apple", "banana", "cherry"}, print whether "banana" is in it and whether "mango" is not.

Q7Adding ItemsEasy

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.

Q8Adding ItemsEasy

Given colours = {"red", "green"}, add several values at once from a list using .update(), then print the set sorted.

Q9Removing ItemsEasy

Using colours = {"red", "green", "blue"}, remove "green" with .remove() and print the result.

Q10Removing ItemsEasyMust Do

Show the difference between .remove() and .discard() when the value is not in the set.

Q11Removing ItemsEasy

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.

Q12Removing ItemsEasy

Empty a set with .clear() and print it with its length.

Q13LoopingEasy

Loop over {"red", "green", "blue"} printing each colour, then do it again in a predictable order.

Q14OrderingEasyMust Do

Show that a set does not support indexing or slicing, and give the correct way to get a specific item out.

Q15UnionEasy

Given a = {1, 2, 3} and b = {3, 4, 5}, print everything that is in either set, using the | operator.

Q16IntersectionEasyMust Do

Using the same two sets, print only the values found in both, using &.

Q17DifferenceEasyMust Do

Print the values that are in a but not in b, then the values in b but not in a.

Q18Symmetric DifferenceEasy

Print the values that are in one set or the other but not both, using ^.

Q19Set MethodsEasy

Repeat the four operations from Q15–Q18 using the method names instead of the operators.

Q20SubsetEasy

Given small = {1, 2} and big = {1, 2, 3, 4}, print whether every item of small is inside big, both with <= and with .issubset().

Q21SupersetEasy

Using the same sets, print whether big contains everything in small, using >= and .issuperset().

Q22DisjointEasy

Print whether {1, 2} and {3, 4} share nothing at all, and whether {1, 2} and {2, 3} do.

Q23ComparisonEasy

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.

Q24AggregationEasy

Given marks = {78, 92, 65, 88, 71}, print the total, highest, lowest and average.

Q25Set vs ListEasy

Put the same values into a list and a set, then print both with their lengths and explain the two differences you can see.

Q26Building SetsMedium

Build a set of the squares of 1 to 10 using a loop and .add(), then print it sorted.

Q27Building SetsMediumMust Do

Remove duplicates from ["b", "a", "c", "a", "b", "d"] while keeping the original order, using a set to remember what has been seen.

Q28In-Place OperationsMediumMust Do

Given a = {1, 2, 3}, fold {3, 4, 5} into it in place using |=, then show .update() does the same thing.

Q29In-Place OperationsMedium

Given a = {1, 2, 3, 4}, cut it down in place to only the values it shares with {3, 4, 5}, using &=.

Q30In-Place OperationsMedium

Given a = {1, 2, 3, 4, 5}, remove several values in one go using -=, then do the same with .difference_update().

Q31In-Place OperationsMedium

Given a = {1, 2, 3}, use ^= to keep only the values that are in exactly one of a and {3, 4, 5}.

Q32UnionMedium

Given three sets of course enrolments, print everyone enrolled in any course, and everyone enrolled in all three.

Q33Set MethodsMedium

Show that .union() accepts a plain list while | does not, and explain when each form is the better choice.

Q34Strings & SetsMedium

Ask for a sentence and print how many distinct words it contains, and the sorted list of them, ignoring case.

Q35IntersectionMedium

Given two sentences, print the words they share, the words unique to each, and how many words are common.

Q36DifferenceMedium

Given two words, print the letters that appear in the first but not the second, and vice versa.

Q37IntersectionMedium

Write vowels_in(word) that returns the set of vowels a word actually contains, then use it on three words.

Q38UniquenessMediumMust Do

Write has_duplicates(items) that returns True when a list contains any repeated value, using a set and no loops.

Q39UniquenessMedium

Now find which values are duplicated in [3, 7, 3, 2, 7, 8, 3], returning them as a set.

Q40HashabilityMedium

Build a set of (name, mark) tuples, including a repeated record, and show the duplicate is dropped.

Q41HashabilityMediumMust Do

Show that a list cannot be put into a set but a tuple can, and explain why in a comment.

Q42frozensetMediumMust Do

Create a frozenset, show it supports all the reading operations, and show it rejects .add().

Q43frozensetMedium

Show that a set cannot contain another set, but can contain a frozenset. Build a set of two frozensets.

Q44Creating SetsMedium

Build a set from a range(), then print the multiples of 3 up to 30 that it contains, using a set operation.

Q45SubsetMediumMust Do

Show the difference between a subset (<=) and a proper subset (<) using two identical sets.

Q46Symmetric DifferenceMedium

Prove that the symmetric difference equals the union with the intersection removed, by computing both ways and comparing.

Q47CopyingMedium

Show that b = a makes an alias of a set while .copy() makes a real copy, using .add() to prove it.

Q48DifferenceMedium

Given a list of all students and a set of those who have paid, print who still owes, sorted.

Q49Functions & SetsMedium

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.

Q50Set vs ListMedium

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".

Q51Real-WorldMediumMust Do

Two courses have enrolment lists. Print who takes both, who takes only Python, who takes only Maths, and the total number of distinct students.

Q52Real-WorldMedium

Given a set of registered students and a list of those who actually attended, report who never turned up and who attended without registering.

Q53Real-WorldMedium

Given two people's friend lists, print their mutual friends, the friends unique to each, and whether they share nobody at all.

Q54Real-WorldMedium

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.

Q55Real-WorldMediumMust Do

Given a small dictionary of known words as a set, check a sentence and report any words that are not recognised.

Q56Real-WorldMediumMust Do

A task needs certain permissions. Given what a user has been granted, report whether they may proceed and exactly what is missing.

Q57Strings & SetsMedium

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.

Q58Strings & SetsMedium

Write all_unique(text) that returns True when no character repeats, ignoring case and spaces, and test it on three strings.

Q59Real-WorldMedium

Compare yesterday's and today's stock lists, reporting which items were added, which were removed, and which stayed.

Q60Real-WorldMedium

Given the winning lottery numbers and a player's ticket, report how many matched, which ones, and the prize tier.

Q61Real-WorldMedium

Given a job's required skills and a candidate's skills, print the match percentage, the gaps, and the extra skills they bring.

Q62Real-WorldMedium

Given survey answers from several people, print how many distinct answers were given and which answers only one person chose.

Q63Real-WorldMedium

Merge a subscribe list and an unsubscribe list into a final mailing list, then report the size change.

Q64Real-WorldMedium

Two restaurant branches have menus. Print the shared dishes, the branch-exclusive dishes, and whether either menu fully covers the other.

Q65Real-WorldMedium

Given a set of blocked words, check a message and report whether it may be posted, listing any blocked words used.

Q66Real-WorldMedium

Given all seat numbers in a row and the seats already booked, print the available seats in order and the occupancy percentage.

Q67HashabilityMediumMust Do

Given a list of (name, email) records containing exact duplicates, remove the duplicates with a set and print the cleaned records sorted.

Q68Symmetric DifferenceMediumMust Do

Two clubs have member lists. Print the students who belong to exactly one club, and separately name which club each of them is in.

Q69UnionMedium

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.

Q70IntersectionMedium

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.

Q71DebuggingHard

This is meant to collect unique tags but crashes on the first .add(). Find and fix the bug.

tags = {}
tags.add("python")
print(tags)
Q72UniquenessHardMust Do

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))
Q73OrderingHard

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)
Q74Removing ItemsHard

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.

Q75DebuggingHardMust Do

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)
Q76Removing ItemsHard

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()}")
Q77Creating SetsHard

Explain why these two lines produce completely different sets, and show how to build each one deliberately.

a = set("hello")
b = {"hello"}
Q78DebuggingHard

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)
Q79AlgorithmsHard

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"))
Q80MembershipHard

Show that float arithmetic can make a membership test fail even when the value looks right, and give a reliable alternative.

Q81PerformanceHardMust Do

Show why membership testing is so much cheaper on a set than a list, by counting the steps a list search actually takes.

Q82PerformanceHard

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.

Q83HashabilityHard

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.

Q84frozensetHard

Given a list of (a, b) pairings where ("Asha", "Raj") and ("Raj", "Asha") mean the same partnership, count the distinct partnerships using frozensets.

Q85ComparisonHard

Show that a set of mixed types can be built but not sorted, and give two ways to print it predictably anyway.

Q86Mini-ProjectMini-Project

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.

Q87Mini-ProjectMini-ProjectMust Do

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.

Q88Mini-ProjectMini-Project

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.

Q89Mini-ProjectMini-Project

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.

Q90Mini-ProjectMini-Project

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.

Q91Mini-ProjectMini-Project

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.

Q92Mini-ProjectMini-Project

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.

Q93Mini-ProjectMini-Project

Build a Vocabulary Comparer for two texts: distinct word counts, shared vocabulary, words unique to each, and a richness score for both.

Q94Mini-ProjectMini-ProjectMust Do

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.

Q95Mini-ProjectMini-Project

Build a Skill Gap Report. Compare several candidates against one job's required and desirable skills, ranking them by how well they match.

Q96InterviewInterview

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.

Q97HashabilityInterview

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.

Q98PerformanceInterview

Explain in your own words how a set achieves near-instant membership testing, and what that costs. Demonstrate the trade-off.

Q99Set vs ListInterview

Give three concrete situations where reaching for a set would be a mistake, and show the right tool for each.

Q100CapstoneInterviewMust Do

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