Practice Questions — Sets in Python
← Back to NotesTopic-Specific Questions
Question 1
Easy
What is the output of the following code?
s = {1, 2, 3, 2, 1}
print(s)
print(len(s))Sets automatically remove duplicate elements.
{1, 2, 3}3Question 2
Easy
What is the output?
s = set("banana")
print(s)
print(len(s))Each unique character in the string becomes a set element.
{'b', 'a', 'n'}3Question 3
Easy
What is the output?
print(type({}))
print(type(set()))Empty curly braces create a dictionary, not a set.
<class 'dict'><class 'set'>Question 4
Easy
What is the output?
s = {1, 2, 3}
s.add(4)
s.add(2)
print(s)
print(len(s))add() adds the element if it does not exist. Adding a duplicate has no effect.
{1, 2, 3, 4}4Question 5
Easy
What is the output?
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b)
print(a | b)& is intersection (common elements). | is union (all elements).
{3}{1, 2, 3, 4, 5}Question 6
Easy
What is the output?
s = {10, 20, 30}
print(20 in s)
print(40 in s)The 'in' operator checks if an element exists in the set.
TrueFalseQuestion 7
Medium
What is the output?
a = {1, 2, 3}
b = {3, 4, 5}
print(a - b)
print(b - a)Set difference is not symmetric. a - b means elements in a but not in b.
{1, 2}{4, 5}Question 8
Medium
What is the output?
a = {1, 2, 3}
b = {3, 4, 5}
print(a ^ b)^ is symmetric difference: elements in either set but not both.
{1, 2, 4, 5}Question 9
Medium
What is the output?
a = {1, 2}
b = {1, 2, 3, 4}
print(a.issubset(b))
print(b.issubset(a))
print(a.issuperset(b))issubset() checks if all elements of a are in b.
TrueFalseFalseQuestion 10
Medium
What is the output?
s = {1, 2, 3}
s.update([3, 4, 5])
print(s)
print(len(s))update() adds all elements from the iterable. Duplicates are ignored.
{1, 2, 3, 4, 5}5Question 11
Medium
What is the output?
s = {1, 2, 3}
s.discard(2)
s.discard(10)
print(s)discard() removes the element if present, does nothing otherwise.
{1, 3}Question 12
Medium
What is the output?
result = {x**2 for x in range(1, 6)}
print(result)
print(type(result))This is a set comprehension, not a dictionary comprehension (no colon).
{1, 4, 9, 16, 25}<class 'set'>Question 13
Hard
What is the output?
a = {1, 2, 3}
b = {1, 2, 3}
print(a == b)
print(a is b)
print(a < b)
print(a <= b)== checks value equality. < checks proper subset. <= checks subset.
TrueFalseFalseTrueQuestion 14
Hard
What is the output?
s = {True, 1, 1.0}
print(s)
print(len(s))In Python, True == 1 == 1.0. Sets treat equal values as duplicates.
{True}1Question 15
Hard
What is the output?
fs = frozenset([1, 2, 3])
print(fs)
print(type(fs))
print(fs | {4, 5})Frozensets support set operations but not mutations.
frozenset({1, 2, 3})<class 'frozenset'>frozenset({1, 2, 3, 4, 5})Question 16
Hard
What is the output?
names = ["Aarav", "Priya", "Aarav", "Rohan", "Priya"]
seen = set()
ordered = []
for name in names:
if name not in seen:
seen.add(name)
ordered.append(name)
print(ordered)This pattern removes duplicates while preserving the original order.
['Aarav', 'Priya', 'Rohan']Question 17
Hard
What is the output?
a = {1, 2, 3}
b = {2, 3, 4}
a &= b
print(a)&= is the in-place intersection operator. It modifies a.
{2, 3}Mixed & Application Questions
Question 1
Easy
What is the output?
nums = [1, 2, 3, 2, 1]
print(list(set(nums)))Converting a list to a set removes duplicates. Converting back gives a list.
[1, 2, 3]Question 2
Easy
What is the output?
s = {"apple", "banana", "cherry"}
print("banana" in s)
print("grape" in s)The 'in' operator checks membership in a set.
TrueFalseQuestion 3
Easy
What is the output?
s = set()
s.add("Aarav")
s.add("Priya")
s.add("Aarav")
print(len(s))
print(s)Adding a duplicate to a set has no effect.
2{'Aarav', 'Priya'}Question 4
Medium
What is the output?
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
only_a = a - b
only_b = b - a
both = a & b
print(f"Only A: {sorted(only_a)}")
print(f"Only B: {sorted(only_b)}")
print(f"Both: {sorted(both)}")Difference gives exclusive elements, intersection gives shared elements.
Only A: [1, 2, 3]Only B: [6, 7, 8]Both: [4, 5]Question 5
Medium
What is the output?
s = {3, 1, 4, 1, 5, 9}
print(sorted(s))
print(min(s), max(s), sum(s))sorted(), min(), max(), and sum() all work on sets.
[1, 3, 4, 5, 9]1 9 22Question 6
Medium
What is the output?
d = {"a": 1, "b": 2, "c": 3}
keys_set = set(d)
print(keys_set)
print("a" in keys_set)Iterating over a dictionary yields its keys.
{'a', 'b', 'c'}TrueQuestion 7
Medium
What is the output?
a = {1, 2, 3}
b = a
b.add(4)
print(a)
print(a is b)Assignment creates an alias, not a copy. Same as with lists and dicts.
{1, 2, 3, 4}TrueQuestion 8
Hard
What is the output?
words = ["hello", "world", "hello", "python", "world"]
unique_lengths = {len(w) for w in words}
print(unique_lengths)This is a set comprehension that computes the length of each word.
{5, 6}Question 9
Medium
What is the difference between
remove() and discard() in sets?Think about what happens when the element does not exist.
remove(element) raises a KeyError if the element is not found. discard(element) does nothing if the element is not found (no error). Both remove the element if it exists.Question 10
Hard
When should you use a set instead of a list?
Think about duplicates, membership testing, and mathematical operations.
Use a set when: (1) you need unique elements with automatic deduplication, (2) you need fast O(1) membership testing, (3) you need mathematical operations like union, intersection, and difference, or (4) order does not matter. Use a list when you need ordering, indexing, or duplicate values.
Question 11
Hard
What is the output?
s1 = frozenset([1, 2, 3])
s2 = frozenset([1, 2, 3])
d = {s1: "first", s2: "second"}
print(d)
print(len(d))frozensets with the same elements are equal and have the same hash.
{frozenset({1, 2, 3}): 'second'}1Question 12
Hard
What is the output?
text = "Aarav likes Maths and Priya likes Science"
words = text.lower().split()
unique_words = set(words)
print(len(words))
print(len(unique_words))
print(sorted(unique_words))Convert to lowercase first so 'Aarav' and 'aarav' are the same.
76['aarav', 'and', 'likes', 'maths', 'priya', 'science']Multiple Choice Questions
MCQ 1
Which of the following creates an empty set?
Answer: D
D is correct. Both
D is correct. Both
set() and set([]) create an empty set. Option A ({}) creates an empty dictionary, not a set.MCQ 2
What is the result of set([1, 2, 2, 3, 3, 3])?
Answer: C
C is correct. Converting a list to a set removes all duplicates. The result is the set {1, 2, 3}. Option A is a list, not a set. Option B is incorrect because sets cannot contain duplicates.
C is correct. Converting a list to a set removes all duplicates. The result is the set {1, 2, 3}. Option A is a list, not a set. Option B is incorrect because sets cannot contain duplicates.
MCQ 3
Which method removes an element from a set WITHOUT raising an error if the element is missing?
Answer: C
C is correct.
C is correct.
discard() silently does nothing if the element is not in the set. remove() (A) raises KeyError. delete() (B) does not exist for sets. pop() (D) removes an arbitrary element.MCQ 4
What does a | b do for two sets a and b?
Answer: C
C is correct.
C is correct.
| is the union operator. It combines all unique elements from both sets. Option A describes intersection (&). Option B describes difference (-). Option D describes symmetric difference (^).MCQ 5
Can a set contain a list as an element?
Answer: B
B is correct. Set elements must be hashable (immutable). Lists are mutable, so they cannot be hashed and cannot be added to a set. Use a tuple instead.
B is correct. Set elements must be hashable (immutable). Lists are mutable, so they cannot be hashed and cannot be added to a set. Use a tuple instead.
MCQ 6
What is the time complexity of checking 'x in my_set'?
Answer: C
C is correct. Sets use hash tables, providing O(1) average-case membership testing. This is much faster than O(n) for lists. This is the primary performance advantage of sets.
C is correct. Sets use hash tables, providing O(1) average-case membership testing. This is much faster than O(n) for lists. This is the primary performance advantage of sets.
MCQ 7
What does a ^ b return for sets?
Answer: C
C is correct.
C is correct.
^ is the symmetric difference operator. It returns elements that are in either set but not in both (the exclusive elements). Option A describes intersection. Option B describes difference.MCQ 8
What is a frozenset?
Answer: B
B is correct. A frozenset is an immutable version of a set. Because it is immutable (and therefore hashable), it can be used as a dictionary key or as an element of another set. It supports all set operations except mutations.
B is correct. A frozenset is an immutable version of a set. Because it is immutable (and therefore hashable), it can be used as a dictionary key or as an element of another set. It supports all set operations except mutations.
MCQ 9
What is the output of {x for x in range(5)}?
Answer: B
B is correct. This is a set comprehension (curly braces with no colon). It creates a set: {0, 1, 2, 3, 4}. Option A would be a list comprehension. Option D would be a dictionary comprehension (requires a colon).
B is correct. This is a set comprehension (curly braces with no colon). It creates a set: {0, 1, 2, 3, 4}. Option A would be a list comprehension. Option D would be a dictionary comprehension (requires a colon).
MCQ 10
What does a.issubset(b) return?
Answer: B
B is correct.
B is correct.
issubset() returns True if every element of a exists in b. Option A describes isdisjoint(). Option C is too restrictive (equal sets are subsets, but non-equal sets can also be subsets). Option D confuses size with containment.MCQ 11
How do you add multiple elements to a set at once?
Answer: C
C is correct.
C is correct.
update() adds all elements from an iterable. add() (A) adds a single element (and would raise TypeError for a list). extend() (B) and append() (D) are list methods, not set methods.MCQ 12
What is the output of {True, 1, 1.0}?
Answer: B
B is correct. In Python,
B is correct. In Python,
True == 1 == 1.0 (they are considered equal for hashing). The set keeps only the first one encountered: True. This is a subtle behavior that catches many people off guard.MCQ 13
Which of the following can be an element of a set?
Answer: C
C is correct. Tuples of immutable elements are hashable and can be set elements. Lists (A), dictionaries (B), and sets (D) are all mutable and unhashable, so they cannot be set elements. Use frozenset instead of a set as an element.
C is correct. Tuples of immutable elements are hashable and can be set elements. Lists (A), dictionaries (B), and sets (D) are all mutable and unhashable, so they cannot be set elements. Use frozenset instead of a set as an element.
MCQ 14
What is the difference between a - b and a ^ b for sets?
Answer: B
B is correct.
B is correct.
a - b (difference) returns elements in a that are not in b. a ^ b (symmetric difference) returns elements that are in either set but not both. For example, if a = {1,2,3} and b = {3,4,5}: a - b = {1,2}, a ^ b = {1,2,4,5}.MCQ 15
What does s.pop() do on a set?
Answer: C
C is correct. Since sets are unordered, there is no concept of first or last.
C is correct. Since sets are unordered, there is no concept of first or last.
pop() removes and returns an arbitrary element. If the set is empty, it raises KeyError.MCQ 16
What is the result of set('aabbc') & set('bbccd')?
Answer: B
B is correct.
B is correct.
set('aabbc') = {'a', 'b', 'c'}. set('bbccd') = {'b', 'c', 'd'}. Intersection (&) returns common elements: {'b', 'c'}. Sets do not have duplicates, so option C is impossible.MCQ 17
What does len({1, 2, 2, 3, 3, 3}) return?
Answer: B
B is correct. The set removes duplicates, leaving {1, 2, 3} with 3 unique elements.
B is correct. The set removes duplicates, leaving {1, 2, 3} with 3 unique elements.
len() returns 3.MCQ 18
What happens when you try to index a set with s[0]?
Answer: C
C is correct. Sets are unordered and do not support indexing.
C is correct. Sets are unordered and do not support indexing.
s[0] raises TypeError: 'set' object is not subscriptable. Use list(s)[0] or iterate if you need to access elements.Coding Challenges
Challenge 1: Remove Duplicates from a List
EasyAarav has a list of roll numbers: [101, 102, 103, 101, 104, 102, 105]. Write a program that removes duplicates and prints the unique roll numbers in sorted order.
Sample Input
(No input required)
Sample Output
[101, 102, 103, 104, 105]
Use set() for deduplication and sorted() for ordering.
roll_numbers = [101, 102, 103, 101, 104, 102, 105]
unique = sorted(set(roll_numbers))
print(unique)Challenge 2: Find Common Elements
EasyPriya has two lists: list1 = [1, 2, 3, 4, 5] and list2 = [4, 5, 6, 7, 8]. Write a program that finds and prints the common elements using sets.
Sample Input
(No input required)
Sample Output
{4, 5}
Use set intersection.
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common = set(list1) & set(list2)
print(common)Challenge 3: Find Unique Characters
EasyWrite a program that takes the string "programming" and prints the number of unique characters and what they are, in sorted order.
Sample Input
(No input required)
Sample Output
Unique characters: 8
['a', 'g', 'i', 'm', 'n', 'o', 'p', 'r']
Use set() and sorted().
text = "programming"
unique = set(text)
print(f"Unique characters: {len(unique)}")
print(sorted(unique))Challenge 4: Students in Only One Club
MediumRohan manages two clubs. maths_club = {'Aarav', 'Priya', 'Meera', 'Vikram'} and science_club = {'Priya', 'Kavya', 'Meera', 'Neha'}. Find students who are in exactly one club (not both).
Sample Input
(No input required)
Sample Output
Students in only one club: {'Aarav', 'Kavya', 'Neha', 'Vikram'}
Use symmetric difference.
maths_club = {'Aarav', 'Priya', 'Meera', 'Vikram'}
science_club = {'Priya', 'Kavya', 'Meera', 'Neha'}
only_one = maths_club ^ science_club
print(f"Students in only one club: {only_one}")Challenge 5: Validate Required Fields
MediumA form requires the fields {'name', 'email', 'phone', 'age'}. A user submitted {'name', 'email', 'city'}. Write a program that finds (a) missing required fields and (b) extra fields that were not required.
Sample Input
(No input required)
Sample Output
Missing fields: {'age', 'phone'}
Extra fields: {'city'}
Use set difference in both directions.
required = {'name', 'email', 'phone', 'age'}
submitted = {'name', 'email', 'city'}
missing = required - submitted
extra = submitted - required
print(f"Missing fields: {missing}")
print(f"Extra fields: {extra}")Challenge 6: Unique Words Across Sentences
MediumGiven two sentences: s1 = 'Aarav likes maths and science' and s2 = 'Priya likes science and coding'. Find the total unique words, words common to both, and words exclusive to each.
Sample Input
(No input required)
Sample Output
All unique words: {'Aarav', 'Priya', 'and', 'coding', 'likes', 'maths', 'science'}
Common words: {'and', 'likes', 'science'}
Only in s1: {'Aarav', 'maths'}
Only in s2: {'Priya', 'coding'}
Use set operations: union, intersection, and difference.
s1 = 'Aarav likes maths and science'
s2 = 'Priya likes science and coding'
words1 = set(s1.split())
words2 = set(s2.split())
print(f"All unique words: {words1 | words2}")
print(f"Common words: {words1 & words2}")
print(f"Only in s1: {words1 - words2}")
print(f"Only in s2: {words2 - words1}")Challenge 7: Order-Preserving Deduplication
MediumGiven the list [5, 3, 1, 3, 2, 5, 4, 1, 2], remove duplicates while preserving the original order of first appearance. Print the result.
Sample Input
(No input required)
Sample Output
[5, 3, 1, 2, 4]
Use a set to track seen elements and a list to maintain order.
nums = [5, 3, 1, 3, 2, 5, 4, 1, 2]
seen = set()
ordered = []
for n in nums:
if n not in seen:
seen.add(n)
ordered.append(n)
print(ordered)Challenge 8: Pangram Checker
HardWrite a program that checks if a given string is a pangram (contains every letter of the alphabet at least once). Test with 'The quick brown fox jumps over the lazy dog'.
Sample Input
(No input required)
Sample Output
Is pangram: True
Missing letters: set()
Use set operations. Compare the set of letters against the full alphabet set.
import string
text = 'The quick brown fox jumps over the lazy dog'
alphabet = set(string.ascii_lowercase)
text_letters = set(text.lower()) & alphabet
is_pangram = text_letters == alphabet
missing = alphabet - text_letters
print(f"Is pangram: {is_pangram}")
print(f"Missing letters: {missing}")Challenge 9: Find Pairs with Given Sum
HardGiven a list [2, 7, 11, 15, 1, 8, 3] and a target sum of 10, find all pairs of numbers that add up to the target. Each number can be used only once per pair.
Sample Input
(No input required)
Sample Output
Pairs that sum to 10: [(2, 8), (7, 3)]
Use a set for O(n) lookup. Track seen numbers.
numbers = [2, 7, 11, 15, 1, 8, 3]
target = 10
seen = set()
pairs = []
for num in numbers:
complement = target - num
if complement in seen:
pairs.append((complement, num))
seen.add(num)
print(f"Pairs that sum to {target}: {pairs}")Challenge 10: Longest Consecutive Sequence
HardGiven the list [100, 4, 200, 1, 3, 2, 5], find the length of the longest consecutive sequence. The sequence does not need to be in order in the original list.
Sample Input
(No input required)
Sample Output
Longest consecutive sequence length: 5
Sequence: [1, 2, 3, 4, 5]
Convert to a set for O(1) lookups. Only start counting from sequence beginnings (numbers with no predecessor in the set).
nums = [100, 4, 200, 1, 3, 2, 5]
num_set = set(nums)
longest = 0
best_start = 0
for num in num_set:
if num - 1 not in num_set: # Start of a sequence
current = num
length = 1
while current + 1 in num_set:
current += 1
length += 1
if length > longest:
longest = length
best_start = num
sequence = list(range(best_start, best_start + longest))
print(f"Longest consecutive sequence length: {longest}")
print(f"Sequence: {sequence}")Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn Python with a live mentor?
Explore our Python course