In Python, the in
keyword is used to check for membership. It is commonly used in an if
statement to determine if a specific value exists within a sequence, such as a list, tuple, string, set, or dictionary keys.
Meaning of in
in an if
Statement
The in
keyword checks whether an element is present in a collection (e.g., list, string, dictionary). If the element is found, it returns True
; otherwise, it returns False
.
Usage Examples
- Checking in a List:
fruits = ["apple", "banana", "cherry"] if "banana" in fruits: print("Banana is in the list!") else: print("Banana is not in the list.")
Output:
Banana is in the list!
- Checking in a String:
text = "Hello, world!" if "world" in text: print("The word 'world' is in the string!")
Output:
The word 'world' is in the string!
- Checking in a Dictionary:
person = {"name": "Alice", "age": 25} if "name" in person: print("The key 'name' exists in the dictionary!")
Output:
The key 'name' exists in the dictionary!
- Checking in a Set:
numbers = {1, 2, 3, 4} if 3 in numbers: print("3 is in the set!")
Output:
3 is in the set!
- Negating with
not in
: You can usenot in
to check if an element is absent from a collection:vowels = "aeiou" if "z" not in vowels: print("The letter 'z' is not a vowel.")
Output:
The letter 'z' is not a vowel.
How It Works
- When
in
is used in anif
statement, Python checks each element in the sequence to see if it matches the value. - For strings, it checks substrings.
- For dictionaries,
in
checks keys by default.
Key Points
in
is case-sensitive. For example,"A"
is not equal to"a"
in strings.- Works with all iterables, including lists, strings, tuples, dictionaries, and sets.
- For dictionaries,
in
checks only the keys, not the values.
Example with Explanation
data = {"apple": 5, "banana": 8}
if "apple" in data:
print("Key 'apple' exists in the dictionary.")
if 8 in data.values():
print("The value 8 exists in the dictionary.")
Output:
Key 'apple' exists in the dictionary.
The value 8 exists in the dictionary.
Here:
in data
checks for keys in the dictionary.in data.values()
checks for values in the dictionary.
This makes the in
keyword highly versatile and commonly used in Python programming.