0
0
Pythonprogramming~10 mins

Set membership testing in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Set membership testing
Start with a set
Check if element in set?
NoReturn False
Yes
Return True
End
The program checks if an element is inside a set and returns True if found, otherwise False.
Execution Sample
Python
my_set = {1, 2, 3}
print(2 in my_set)
print(5 in my_set)
This code tests if 2 and 5 are members of the set {1, 2, 3} and prints the results.
Execution Table
StepExpressionEvaluationResultOutput
1my_set = {1, 2, 3}Create set with elements 1, 2, 3{1, 2, 3}
22 in my_setIs 2 in {1, 2, 3}?TrueTrue
35 in my_setIs 5 in {1, 2, 3}?FalseFalse
💡 All membership tests completed and results printed.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
my_setundefined{1, 2, 3}{1, 2, 3}{1, 2, 3}
2 in my_setundefinedundefinedTrueTrue
5 in my_setundefinedundefinedundefinedFalse
Key Moments - 2 Insights
Why does '2 in my_set' return True but '5 in my_set' returns False?
Because 2 is an element inside the set {1, 2, 3} (see step 2 in execution_table), but 5 is not (see step 3).
Is the set changed after membership testing?
No, the set remains the same throughout (see variable_tracker for 'my_set' values). Membership testing only checks presence.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the result of '2 in my_set'?
ATrue
BFalse
CError
DNone
💡 Hint
Check the 'Result' column in execution_table row for step 2.
At which step does the membership test return False?
AStep 2
BStep 3
CStep 1
DNo step returns False
💡 Hint
Look at the 'Result' column in execution_table for each step.
If we test '3 in my_set', what would be the expected output?
AError
BFalse
CTrue
DNone
💡 Hint
Refer to variable_tracker to see if 3 is in the set {1, 2, 3}.
Concept Snapshot
Set membership testing syntax:
  element in set
Returns True if element is in the set, else False.
Sets are unordered collections of unique elements.
Membership testing is fast and simple.
Use it to check presence without changing the set.
Full Transcript
This lesson shows how Python checks if an element is inside a set using the 'in' keyword. We start by creating a set with elements 1, 2, and 3. Then we test if 2 is in the set, which returns True because 2 is present. Next, we test if 5 is in the set, which returns False because 5 is not present. The set itself does not change during these tests. This is a quick way to check membership in a collection.