← Core Concepts
Concept
The 'in' operator — check membership
Check if an item exists in a sequence or collection.
Check in lists
fruits = ['apple', 'banana', 'cherry']
if 'apple' in fruits:
print("Found apple")
if 'orange' not in fruits:
print("No orange")
Check in strings
text = "Hello World"
if 'World' in text:
print("Found 'World'")
if 'x' not in text:
print("No 'x' in text")
Check in dictionaries
person = {'name': 'Alice', 'age': 30}
# Check keys:
if 'name' in person:
print("Has name key")
# Check values (less common):
if 'Alice' in person.values():
print("Alice is a value")
Check in sets
numbers = {1, 2, 3, 4, 5}
if 3 in numbers:
print("3 is in the set")
# Very fast for sets (O(1) average)
With loops
# Common pattern:
items = [1, 2, 3, 4, 5]
target = 3
if target in items:
print(f"Found {target} at index {items.index(target)}")
else:
print("Not found")
Performance note
- Lists: O(n) — checks each item
- Sets/Dicts: O(1) average — very fast
- Strings: O(n) — checks each character