Membership Operator¶
The in operator checks if a value exists in a collection.
With Lists¶
let nums = [10, 20, 30, 40, 50]
if 20 in nums:
print("Found 20!")
if 99 in nums:
print("Won't print - 99 not in list")
With Sets¶
With Strings (Substring Check)¶
let message = "Hello, World!"
if "World" in message:
print("Found 'World' in message")
if "Desi" in message:
print("Won't print")
With Tuples¶
Custom Classes¶
Classes can implement __contains__ to support the in operator:
class MySet:
pub data: list[int]
pub def __new__(self, values: list[int]):
self.data = values
pub def __contains__(self, item: int) -> bool:
# Custom logic to check membership
for x in self.data:
if x == item:
return true
return false
let s = MySet([10, 20, 30, 40, 50])
if 20 in s:
print("20 is in MySet") # This prints
if 99 in s:
print("Won't print")
Tip
The __contains__ method decides how to compare elements. Use value equality (like ==) for intuitive behavior.
Negation¶
Negate the whole membership test with not:
There is no not in operator
Python's x not in y is not Desi syntax. Write not (x in y) — the
parentheses are required, because not binds tighter than in.