VMware ESXi and vSphere Cluster Management
Check Whether a Value Is in a Python List
Learn how to use Python's in and not in operators to check list membership, validate input, detect duplicates, and compare values correctly.
A list is an ordered Python collection that can contain multiple values. A membership test checks whether a particular value occurs among the items in that list.
Python provides the in and not in membership operators for this purpose. Their results are Boolean values: either True or False.
Use in to check list membership
The standard membership expression has this form:
value in list_name
Put the value you are searching for on the left and the list on the right:
colors = ["red", "green", "blue"]
print("green" in colors)
print("yellow" in colors)
Output:
True
False
Python compares the searched value with the items in colors. Because "green" is an item in the list, the first expression produces True. Because "yellow" is not an item, the second expression produces False.
Store or use the Boolean result
A membership expression can be stored in a Boolean variable:
allowed_values = [10, 20, 30]
selected_value = 20
is_allowed = selected_value in allowed_values
print(is_allowed) # True
You can also use the expression directly as the condition of an if statement.
Use membership tests with if and else
An if statement runs code when its condition is True. This makes membership tests useful when different actions are needed depending on whether a value exists.
registered_names = ["Tanya", "Marco", "Priya"]
proposed_name = "Tanya"
if proposed_name in registered_names:
print("That name is already registered.")
else:
print("That name is available.")
Since "Tanya" is already an item in the list, the program prints:
That name is already registered.
Detect a duplicate username
This pattern can reject a proposed username when it already appears among existing usernames:
existing_usernames = ["river", "pixel", "maple"]
proposed_username = "pixel"
if proposed_username in existing_usernames:
print("Please choose another username.")
else:
print("Username is available.")
The condition detects the duplicate before the new username is accepted.
Use not in to check for absence
not in is the inverse membership operator. It returns True when the searched value does not occur in the list, and False when it does occur.
registered_names = ["Tanya", "Marco", "Priya"]
proposed_name = "Alex"
if proposed_name not in registered_names:
print("You can use this name.")
else:
print("Please choose another name.")
Because "Alex" is absent, the not in condition is True.
Exact matching behavior
For a list, in checks whether the searched value is equal to a complete list item. It does not automatically search for arbitrary text inside each string item.
names = ["Tanya Smith", "Marco Lee"]
print("Tanya Smith" in names) # True
print("Tanya" in names) # False
"Tanya Smith" is a complete item. "Tanya" is only part of that item, so it is not considered a matching list element.
String comparisons are case-sensitive by default. This means uppercase and lowercase letters are treated as different:
names = ["Tanya", "Marco"]
print("Tanya" in names) # True
print("tanya" in names) # False
If your application should treat capitalization as unimportant, normalize both the stored values and the searched value before comparing:
names = ["Tanya", "Marco"]
proposed_name = "tanya"
normalized_names = [name.casefold() for name in names]
if proposed_name.casefold() in normalized_names:
print("That name is already registered.")
casefold() creates a lowercase-like form intended for case-insensitive text comparisons. Using consistent capitalization when storing and checking names is another simple option.
Membership with numbers and other value types
Membership tests work with numbers, strings, and other values that can be compared for equality. During the test, Python performs an equality comparison between the searched value and list items.
permitted_numbers = [1, 3, 5, 7]
print(3 in permitted_numbers) # True
print(4 in permitted_numbers) # False
The types must also match the intended data. The integer 3 and the string "3" are different values:
numbers = [1, 2, 3]
print(3 in numbers) # True
print("3" in numbers) # False
When input comes from input(), it is a string by default. Convert it when the list contains integers:
permitted_numbers = [1, 3, 5]
selected_number = int(input("Choose a permitted number: "))
if selected_number in permitted_numbers:
print("That number is permitted.")
else:
print("That number is not permitted.")
Input validation with in and not in
Membership checks are useful for validating that a response is one of the permitted choices:
valid_choices = ["yes", "no"]
answer = input("Continue? Enter yes or no: ")
if answer not in valid_choices:
print("Please enter yes or no.")
else:
print("Your answer is valid.")
For case-insensitive input, normalize the response:
valid_choices = ["yes", "no"]
answer = input("Continue? Enter yes or no: ").strip().casefold()
if answer not in valid_choices:
print("Please enter yes or no.")
else:
print("Your answer is valid.")
strip() removes extra whitespace at the beginning and end. The membership test then compares the cleaned value with the allowed list.
Troubleshooting membership tests
A name appears in the list, but the result is False
Check capitalization and extra whitespace. For example, "tanya" does not equal "Tanya". Use consistent capitalization, call strip() to remove unwanted whitespace, or normalize both sides before comparing.
A numeric membership test unexpectedly returns False
Check whether one value is a string and the other is an integer. Convert input to the intended type, such as with int(), before testing membership.
A partial word was expected to match
in applied to a list checks complete list elements. It does not search inside each string element. To search within individual strings, use a loop and a string operation:
names = ["Tanya Smith", "Marco Lee"]
for name in names:
if "Tanya" in name:
print(name)
The membership expression is reversed
Use the searched value on the left and the list on the right:
searched_value in list_name
For example, write "blue" in colors, not colors in "blue".
Key points
- A membership test checks whether a value occurs in a collection.
- Use
value in list_nameto test for presence. - Use
value not in list_nameto test for absence. - Both operators produce a Boolean result:
TrueorFalse. - The searched value goes on the left and the list goes on the right.
- List membership compares complete items using equality.
- String comparisons are case-sensitive unless you normalize the values.
- Keep data types consistent, such as integer
3versus string"3".