0
0
Pythonprogramming~5 mins

Set membership testing in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the in keyword do when used with a set in Python?
It checks if a value is present in the set and returns True if it is, otherwise False.
Click to reveal answer
beginner
How do you check if an element is NOT in a set?
Use the not in keyword. For example, if element not in my_set: checks if element is not a member of my_set.
Click to reveal answer
intermediate
Why is set membership testing faster than list membership testing?
Sets use a hash table internally, so checking membership is on average very fast (constant time), while lists check each item one by one (linear time).
Click to reveal answer
beginner
What will be the output of this code?
my_set = {1, 2, 3}
print(2 in my_set)
print(5 in my_set)
True
False

Because 2 is in the set but 5 is not.
Click to reveal answer
beginner
Can you use the in keyword to check membership in other data types besides sets?
Yes! You can use in with lists, tuples, strings, dictionaries (checks keys), and more.
Click to reveal answer
What does element in my_set return if element is not in my_set?
ARaises an error
BFalse
CNone
DTrue
Which data structure generally provides the fastest membership testing?
ASet
BTuple
CList
DString
What keyword checks if an item is NOT in a set?
Anot in
Bnot
Cout
Dno in
What will print('a' in {'a', 'b', 'c'}) output?
AError
BFalse
CTrue
DNone
Which of these is NOT a valid use of in for membership testing?
AChecking if a key is in a dictionary
BChecking if a value is in a list
CChecking if a character is in a string
DChecking if a number is in an integer
Explain how to check if an item is in a set and why this is efficient.
Think about how sets store items differently than lists.
You got /3 concepts.
    Describe the difference between using 'in' and 'not in' with sets.
    One checks if something is there, the other checks if it is missing.
    You got /3 concepts.