0
0
Pythonprogramming~10 mins

Adding and removing set elements in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Adding and removing set elements
Start with empty set
Add element with add()
Check if element exists
Remove element with remove() or discard()
Set updated
End
This flow shows starting with a set, adding elements, checking existence, removing elements, and ending with the updated set.
Execution Sample
Python
s = set()
s.add(10)
s.add(20)
s.remove(10)
print(s)
This code creates a set, adds two elements, removes one, and prints the final set.
Execution Table
StepActionSet ContentOutput/Note
1Create empty set sset()Set is empty
2Add 10 with s.add(10){10}10 added
3Add 20 with s.add(20){10, 20}20 added
4Remove 10 with s.remove(10){20}10 removed
5Print s{20}Outputs: {20}
💡 Program ends after printing the set with one element {20}
Variable Tracker
VariableStartAfter 1After 2After 3Final
sset(){10}{10, 20}{20}{20}
Key Moments - 2 Insights
What happens if we try to remove an element not in the set?
Using remove() on a missing element causes an error, but discard() does not. See step 4 where remove(10) works because 10 is present.
Does adding the same element twice change the set?
No, sets only keep unique elements. Adding 10 twice would not add a second 10. This is why after step 2, adding 10 again would not change the set.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the content of set s after step 3?
A{20}
B{10, 20}
C{10}
D{}
💡 Hint
Check the 'Set Content' column at step 3 in the execution_table.
At which step is the element 10 removed from the set?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' column describing removal in the execution_table.
If we replace s.remove(10) with s.discard(30), what happens?
ANo error, set remains unchanged
BError occurs because 30 is not in the set
C30 is added to the set
DSet becomes empty
💡 Hint
Recall that discard() does not raise an error if the element is missing, unlike remove().
Concept Snapshot
Set operations:
- Create: s = set()
- Add element: s.add(x)
- Remove element: s.remove(x) (error if missing)
- Remove safely: s.discard(x) (no error if missing)
- Sets hold unique elements only
Full Transcript
This visual execution shows how to add and remove elements from a Python set. We start with an empty set, add elements 10 and 20, then remove 10. The set updates after each operation. Removing an element not in the set with remove() causes an error, but discard() avoids errors. Adding the same element twice does not duplicate it. The final printed set contains only 20.