Set Membership¶
Zero-dependency Python snippets for checking membership in sets using the standard library.
3 snippets available in this sub-category.
Simple¶
Check if item is in set¶
set
membership
in
contains
data-structures
Check if an element exists in a set
fruits = {"apple", "banana", "cherry"}
print("banana" in fruits) # True
print("orange" in fruits) # False
Notes
- Membership checks are O(1) on average
- Much faster than checking in a list for large collections
Not in set¶
set
not-in
membership
data-structures
Check if an element does not exist in a set
Notes
- Use
not in
for negative membership
Complex¶
Set membership with custom objects¶
set
membership
custom
object
hash
data-structures
Check membership for custom objects in a set
class User:
def __init__(self, name):
self.name = name
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return isinstance(other, User) and self.name == other.name
users = {User("alice"), User("bob")}
print(User("alice") in users) # True
print(User("carol") in users) # False
Notes
- Custom objects must implement hash and eq for set membership
- Useful for deduplication of custom types
🔗 Cross Reference¶
- Reference: See 📂 Add and remove items from set
🏷️ Tags¶
set
, membership
, in
, not-in
, custom
, data-structures
📝 Notes¶
- Use
in
andnot in
for fast membership checks - Sets are ideal for large membership tests