19. Sets

A set in Python is used to store multiple unique items in a single variable.
Sets are unordered, unchangeable (you cannot change existing items, but you can add or remove items), and unindexed.
Sets are created using curly braces {}, but unlike dictionaries, they contain individual items separated by commas rather than key-value pairs.
Sets automatically remove any duplicate values—every item in a set must be unique!
# Creating a simple set of numbers (duplicates are automatically ignored)
numbers = {1, 2, 3, 3, 4}  # Result: {1, 2, 3, 4}

19.1. Adding Items to a Set

To add new items to an existing set, Python gives us two primary methods:

  • .add(item): Adds a single item to the set.

  • .update(iterable): Adds multiple items from another set, list, or iterable to the current set.

inventory = {"sword", "shield"}

# Adds "potion" to the set
inventory.add("potion")      # Result: {"sword", "shield", "potion"}

# Adding a duplicate item does nothing because set items must be unique
inventory.add("sword")       # Result: {"sword", "shield", "potion"}

# Adds multiple items from another set
more_items = {"bow", "arrow"}
inventory.update(more_items) # Result: {"sword", "shield", "potion", "bow", "arrow"}

19.1.1. Quiz: Adding Items

19.1.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
.add()
.update()
braces
duplicate
unordered

1. Sets in Python are created using curly Drop here.
2. To add a single item to a set, call the Drop here method.
3. To add multiple items from another set or list, call the Drop here method.
4. A key property of sets is that they automatically remove Drop here values.
5. Sets do not preserve item order, which means they are Drop here.

19.1.1.2. Code Ordering Examples

Example 1: Create a set of primary colors, add a new color, and print the set.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(colors)
☰
colors.add("yellow")
☰
colors = {"red", "blue"}

Example 2: Create a fruit set, attempt to add a duplicate fruit, and print the set.

Drag and drop lines into the correct order and click to adjust indentation:
☰
fruits.add("apple")
☰
fruits = {"apple", "banana"}
☰
print(fruits)

Example 3: Create a set of items, update it with another set of items, and print the total set.

Drag and drop lines into the correct order and click to adjust indentation:
☰
gear.update(extra_gear)
☰
print(gear)
☰
gear = {"helmet"}
☰
extra_gear = {"boots", "gloves"}

19.1.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

Which method adds a single item to a Python set?

Correct! .add() places one single item into a set.

Incorrect. .append() is a list method, not a set method.

Incorrect. Sets are unordered and do not support index positions.

Incorrect. .push() is not a Python set method.

What happens when you run nums = {1, 2}; nums.add(2)?

Incorrect. Sets cannot contain duplicate values.

Correct! Adding an existing item has no effect on a set.

Incorrect. Adding a duplicate is ignored safely without errors.

Incorrect. .add() does not delete existing values.

Which character symbol is used to define a set in Python?

Correct! Sets are defined using curly braces {}.

Incorrect. Square brackets are used for lists.

Incorrect. Parentheses are used for tuples.

Incorrect. Angle brackets are comparison operators.

What is the difference between .add() and .update() for sets?

Correct! .add() takes one item, whereas .update() unpacks multiple items.

Incorrect. Both work with any valid data types.

Incorrect. Sets are always unordered.

Incorrect. They handle single vs multiple items differently.

What will items = {"pen"}; items.update(["ruler", "eraser"]); print(len(items)) output?

Incorrect. Two new items were added.

Incorrect. The original item “pen” remains in the set.

Correct! “pen”, “ruler”, and “eraser” make 3 unique items.

Incorrect. Exactly 2 items were added to 1 existing item.

Why do Python sets NOT support index positions like my_set[0]?

Correct! Sets have no deterministic index order.

Incorrect. Sets can store strings, floats, and booleans.

Incorrect. Unordered structure is the reason indexing is unsupported.

Incorrect. Indexing a set raises a TypeError.

How do you add multiple items from new_scores into an existing set all_scores?

Incorrect. .add() would treat the whole collection as a single element or fail.

Incorrect. .insert() is a list method requiring an index.

Incorrect. Sets use .update(), not .extend().

Correct! .update() merges elements from new_scores into all_scores.

What is the result of len({"apple", "apple", "banana"})?

Incorrect. Duplicate “apple” entries are automatically merged.

Correct! “apple” and “banana” make 2 unique items.

Incorrect. “banana” is also in the set.

Incorrect. Defining duplicates in set literals is valid syntax.

Given nums = {10, 30}, which command adds 20 to the set?

Incorrect. Sets do not support .insert().

Correct! .add(20) places 20 into the set.

Incorrect. Sets do not have an .append() method.

Incorrect. .push() is not a set method.

What happens if you run data = {1, 2}; data.update("34")?

Correct! Strings are iterables, so .update() adds each character separately.

Incorrect. .update() iterates through string characters.

Incorrect. Strings are valid iterables for .update().

Incorrect. Characters added from strings are string types.

Question 1 of 0

19.2. Deleting Items from a Set

Python provides several ways to remove items from a set:

  • .remove(item): Deletes the item. Raises a KeyError if the item is not found.

  • .discard(item): Deletes the item, but does NOT raise an error if the item is missing.

  • .pop(): Removes and returns an arbitrary (random) item because sets are unordered.

  • .clear(): Removes all items from the set, leaving it completely empty.

pets = {"dog", "cat", "fish"}

# Removes "cat" by value
pets.remove("cat")    # Result: {"dog", "fish"}

# Safely removes "bird" without error even though it isn't in the set
pets.discard("bird")  # Result: {"dog", "fish"}

# Removes and returns a random item
removed_pet = pets.pop()

# Wipes all remaining items from the set
pets.clear()          # Result: set()

19.2.1. Quiz: Deleting Items

19.2.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
.discard()
.pop()
.remove()
KeyError
set()

1. To delete an item from a set and throw an error if it isn't present, use the Drop here method.
2. To safely remove an item without throwing an error if it is missing, use the Drop here method.
3. The Drop here method removes and returns a random item from a set.
4. Attempting to ``.remove()`` an item that does not exist in a set raises a Drop here.
5. An empty set is displayed by Python as Drop here rather than ``{}`` (which creates an empty dictionary).

19.2.1.2. Code Ordering Examples

Example 1: Create a set of animals, remove “dog”, and print the remaining set.

Drag and drop lines into the correct order and click to adjust indentation:
☰
animals = {"cat", "dog", "bird"}
☰
print(animals)
☰
animals.remove("dog")

Example 2: Create a scores set, safely discard a non-existent score, and print the set.

Drag and drop lines into the correct order and click to adjust indentation:
☰
scores = {100, 85, 90}
☰
print(scores)
☰
scores.discard(50)

Example 3: Create a set of colors, pop a random color, and print the popped item.

Drag and drop lines into the correct order and click to adjust indentation:
☰
popped_color = colors.pop()
☰
print(popped_color)
☰
colors = {"red", "green", "blue"}

19.2.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

What error occurs if you use .remove() on an item that does NOT exist in a set?

Correct! .remove() raises a KeyError when the item is missing.

Incorrect. Lists raise ValueError, but sets raise KeyError.

Incorrect. Sets do not use index positions.

Incorrect. The syntax is valid, but the key was not found.

Which method safely deletes an item from a set WITHOUT raising an error if it is missing?

Incorrect. .remove() throws a KeyError if missing.

Correct! .discard() ignores missing items silently.

Incorrect. .pop() removes a random item and errors on empty sets.

Incorrect. No such method exists on sets.

Why does .pop() on a set remove an arbitrary (random) item instead of the last item?

Correct! Unordered sets have no defined start or end position.

Incorrect. Unordered nature is the core reason.

Incorrect. .pop() takes no index argument on sets.

Incorrect. Set elements are unordered.

What is the result of items = {"apple"}; items.discard("banana")?

Correct! .discard() safely ignores missing items.

Incorrect. .discard() does not raise KeyErrors.

Incorrect. .discard() is safe from missing item errors.

Incorrect. “apple” is not removed.

How do you remove ALL items from a set named data so it becomes empty set()?

Incorrect. .remove() requires an item parameter.

Incorrect. .pop() takes no arguments for sets.

Correct! .clear() empties all elements from a set.

Incorrect. del data deletes the variable entirely.

Why is an empty set represented as set() instead of {} in Python?

Correct! Python treats {} as an empty dictionary by default.

Incorrect. Sets can be empty.

Incorrect. Sets use curly braces when non-empty.

Incorrect. It is intentional design to prevent syntax ambiguity.

Given letters = {"a", "b", "c"}, what does letters.clear(); print(letters) output?

Incorrect. {} represents an empty dictionary.

Correct! Python prints set() to represent an empty set.

Incorrect. The variable still holds an empty set object.

Incorrect. .clear() is valid syntax.

What happens if you execute .pop() on an EMPTY set?

Incorrect. Python raises an exception.

Correct! Calling .pop() on an empty set raises a KeyError.

Incorrect. An exception is raised.

Incorrect. .pop() cannot create elements.

Which statement about .remove() vs .discard() is true?

Correct! That is the primary functional difference.

Incorrect. Neither method returns a value.

Incorrect. Both work with any valid data types.

Incorrect. Their behavior with missing items differs.

Given numbers = {1, 2, 3}, what will numbers.remove(2); print(2 in numbers) output?

Incorrect. 2 was removed.

Correct! 2 is no longer present in the set.

Incorrect. in operator yields booleans.

Incorrect. Checking with in evaluates cleanly to False.

Question 1 of 0

19.3. Set Operations (Union, Intersection, Difference)

Sets let us perform powerful mathematical operations to compare two sets:

  • setA.union(setB) or setA | setB: Combines all unique items from both sets.

  • setA.intersection(setB) or setA & setB: Finds items that exist in both sets.

  • setA.difference(setB) or setA - setB: Finds items in setA that are NOT in setB.

group_a = {"Alex", "Sam", "Jordan"}
group_b = {"Sam", "Taylor", "Morgan"}

# All unique people across both groups
all_people = group_a.union(group_b)
# Result: {"Alex", "Sam", "Jordan", "Taylor", "Morgan"}

# People who are in BOTH groups
both = group_a.intersection(group_b)
# Result: {"Sam"}

# People only in group A, but not in group B
only_a = group_a.difference(group_b)
# Result: {"Alex", "Jordan"}

19.3.1. Quiz: Set Operations

19.3.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
.difference()
.intersection()
.union()
ampersand
pipe

1. To combine all unique items from two sets together, use the Drop here method.
2. To find items that are shared in both sets, use the Drop here method.
3. To find items present in the first set but absent from the second set, use the Drop here method.
4. The shorthand symbol operator for set union is the Drop here symbol |.
5. The shorthand symbol operator for set intersection is the Drop here symbol &.

19.3.1.2. Code Ordering Examples

Example 1: Create two sets, find their union, and print the result.

Drag and drop lines into the correct order and click to adjust indentation:
☰
set1 = {1, 2}
☰
combined = set1.union(set2)
☰
print(combined)
☰
set2 = {2, 3}

Example 2: Create two sets, find their common elements using intersection, and print them.

Drag and drop lines into the correct order and click to adjust indentation:
☰
a = {"cat", "dog"}
☰
common = a.intersection(b)
☰
b = {"dog", "fish"}
☰
print(common)

Example 3: Create two sets, find the difference (items in A not in B), and print them.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(diff)
☰
a = {10, 20, 30}
☰
diff = a.difference(b)
☰
b = {20, 40}

19.3.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

Which set operation returns all items that appear in BOTH sets?

Correct! .intersection() identifies shared items.

Incorrect. .union() combines all unique items.

Incorrect. .difference() finds items unique to one set.

Incorrect. .update() modifies a set in place.

What is the result of {1, 2}.union({2, 3})?

Incorrect. Sets eliminate duplicate values.

Correct! Union combines unique elements across sets.

Incorrect. {2} is the intersection, not the union.

Incorrect. {1, 3} is the symmetric difference.

What symbol operator is equivalent to calling .intersection() between two sets?

Incorrect. | is the union operator.

Correct! The ampersand symbol & computes set intersection.

Incorrect. - is the difference operator.

Incorrect. Sets do not support the + operator.

Given a = {1, 2, 3} and b = {2, 3, 4}, what does a.difference(b) return?

Correct! 1 is the only item in set a that is absent from set b.

Incorrect. 4 is in b, but difference calculates items in a NOT in b.

Incorrect. {2, 3} is the intersection.

Incorrect. That would be symmetric difference.

What happens if you try to concatenate two sets using the + operator, like {1} + {2}?

Incorrect. Sets do not support + for joining.

Correct! Combining sets requires .union() or the | operator.

Incorrect. Sets do not add values numerically with +.

Incorrect. TypeError is raised.

Which operator symbol performs set union?

Correct! The pipe symbol | computes the union of two sets.

Incorrect. & computes intersection.

Incorrect. ^ computes symmetric difference.

Incorrect. % is the modulus operator.

Given x = {"a", "b"} and y = {"c"}, what is x & y?

Incorrect. & computes intersection.

Correct! No elements are shared between x and y, leaving an empty set.

Incorrect. “a” is not in y.

Incorrect. Valid set operation.

What is the outcome of {10, 20} - {20, 30}?

Correct! The difference operator - keeps elements from the left set not in the right set.

Incorrect. Difference evaluates items in the left operand only.

Incorrect. 20 is subtracted out.

Incorrect. 20 is removed because it is present in the right set.

If setA = {1, 2} and setB = {1, 2}, what is setA.intersection(setB)?

Incorrect. Both sets share all elements.

Correct! All elements are present in both sets.

Incorrect. 2 is also in both sets.

Incorrect. 1 is also in both sets.

Which method creates a NEW set containing elements in set A or set B, but NOT both?

Incorrect. Union includes all elements.

Incorrect. Intersection includes only common elements.

Correct! Symmetric difference selects items unique to each set.

Incorrect. Difference checks items in one direction only.

Question 1 of 0

19.4. Iterating Through a Set

Iterating means stepping through items in a set one by one using a for loop. Because sets are unordered, items may appear in any random order during iteration!

players = {"Alex", "Sam", "Jordan"}

# Loop through each item in the set
for player in players:
    print(f"Player: {player}")

19.4.1. Quiz: Iterating Through Sets

19.4.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
colon
for
indentation
len()
unpredictable

1. To step through each item in a set one by one, use a Drop here loop.
2. Because sets are unordered, the order of items printed during iteration is Drop here.
3. The header line of a set ``for`` loop must end with a Drop here.
4. Code inside the loop body must use four spaces of Drop here.
5. The built-in function Drop here can be used to find how many iterations a loop over a set will make.

19.4.1.2. Code Ordering Examples

Example 1: Create a set of fruits and use a for loop to print each fruit.

Drag and drop lines into the correct order and click to adjust indentation:
☰
for fruit in fruits:
☰
fruits = {"apple", "banana", "cherry"}
☰
print(fruit)

Example 2: Create a set of numbers, calculate their double in a loop, and print each doubled value.

Drag and drop lines into the correct order and click to adjust indentation:
☰
numbers = {1, 2, 3}
☰
double_val = n * 2
☰
for n in numbers:
☰
print(double_val)

Example 3: Check membership while looping through a set of names and print matched items.

Drag and drop lines into the correct order and click to adjust indentation:
☰
if name == "Alice":
☰
for name in names:
☰
print("Found Alice!")
☰
names = {"Alice", "Bob"}

19.4.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

What should you expect about the output order when looping through a set with for item in my_set:?

Correct! Sets are unordered collections.

Incorrect. Sets do not sort automatically.

Incorrect. Sets do not keep insertion order.

Incorrect. Set iteration order is non-deterministic.

How many times will a for loop execute over s = {10, 20, 20, 30}?

Incorrect. The duplicate 20 is eliminated when the set is created.

Correct! The set contains 3 unique items ({10, 20, 30}).

Incorrect. There are 3 unique values.

Incorrect. It loops through all unique items.

What operator checks if an item exists inside a set during or before iteration?

Incorrect. Python uses in.

Correct! The in keyword checks set membership very fast.

Incorrect. contains is not a keyword.

Incorrect. exists is not a keyword.

Why is checking item in my_set faster than item in my_list for large datasets?

Correct! Set membership lookup speed does not depend on dataset size.

Incorrect. Sets are unordered.

Incorrect. Both reside in memory.

Incorrect. Set membership checks are significantly faster.

What error occurs if you forget to indent code inside a set for loop body?

Correct! Python requires indented blocks after colons.

Incorrect. KeyErrors occur with missing set/dict items.

Incorrect. Python raises a specific IndentationError.

Incorrect. Indentation governs structural blocks.

Which function tells you how many elements a loop over a set will visit?

Incorrect. Sets do not have a count method.

Correct! len(my_set) returns the total number of unique elements.

Incorrect. size() is not built into Python.

Incorrect. total() is not built into Python.

What will for x in {"a", "b"}: print(x, end="") print?

Incorrect. Because sets are unordered, output could be “ab” or “ba”.

Correct! Unordered iteration means character order is unpredictable.

Incorrect. The loop prints items individually.

Incorrect. Valid loop syntax.

Question 1 of 0