Loading...
Loading...
Check if items exist in collections with in/not in
Two powerful Python operators let you check belonging and sameness:
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Banana is in the list!")
if "grape" not in fruits:
print("No grapes here.")a = None
b = None
if a is None:
print("a has no value!")
if a is b:
print("a and b are the same object")in works with any collection ā lists, strings, tuples, dictionaries, sets:
# Check in a string
text = "Hello, World!"
print("World" in text) # True
print("Python" in text) # False
# Check in a list
colors = ["red", "green", "blue"]
print("red" in colors) # True
# Check in a dictionary (checks keys by default)
person = {"name": "Alice", "age": 25}
print("name" in person) # True
print("Alice" in person) # False ā Alice is a value, not a keyThis is a crucial distinction:
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True ā same values
print(a is b) # False ā different lists in memory
print(a is c) # True ā c points to the same list as a| ā Wrong | Why | ā Right |
|---|---|---|
| `if "banana" in fruits == True` | Redundant ā `in` already returns a boolean | `if "banana" in fruits:` |
| `if a is 5` | `is` checks identity, not value ā use `==` for numbers | `if a == 5:` |
| `if not "a" in text` | Works but reads awkwardly | `if "a" not in text:` (Python supports `not in`) |
| `if result == None` | Works but unconventional | `if result is None:` |
Create a list called todo_list with 3-4 tasks. Then:
todo_list = ["laundry", "dishes", "groceries"]
print("laundry" in todo_list)
print("sleep" not in todo_list)
password = "secret123"
print("secret" in password)