Python Check if a Number is in a List
We can use Python'sinkeyword to check whether a number exists in a list.inThe keyword returns a boolean value. If the number is in the list, it returnsTrue, otherwise it returnsFalse。
Example
# Define a list
numbers = [1, 2, 3, 4, 5]
# The number to check
num_to_check = 3
# Check if the number is in the list
if num_to_check in numbers:
print(f"{num_to_check} is in the list")
else:
print(f"{num_to_check} is not in the list")
numbers = [1, 2, 3, 4, 5]
# The number to check
num_to_check = 3
# Check if the number is in the list
if num_to_check in numbers:
print(f"{num_to_check} is in the list")
else:
print(f"{num_to_check} is not in the list")
Code Analysis:
numbers = [1, 2, 3, 4, 5]: Define a list containing numbers.num_to_check = 3: Define the number to check.if num_to_check in numbers:: Use theinkeyword to checknum_to_checkwhethernumbersis in the list.print(f"{num_to_check} 在列表中"): If the number is in the list, print the corresponding message.else:: If the number is not in the list, executeelsethe code in the block.print(f"{num_to_check} 不在列表中"): If the number is not in the list, print the corresponding message.
Output:
3 在列表中Other Extensions
Python3 Examples