Python Check if a Number is in a List

Document 对象参考手册Python3 Examples

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")

Code Analysis:

  1. numbers = [1, 2, 3, 4, 5]: Define a list containing numbers.
  2. num_to_check = 3: Define the number to check.
  3. if num_to_check in numbers:: Use theinkeyword to checknum_to_checkwhethernumbersis in the list.
  4. print(f"{num_to_check} 在列表中"): If the number is in the list, print the corresponding message.
  5. else:: If the number is not in the list, executeelsethe code in the block.
  6. print(f"{num_to_check} 不在列表中"): If the number is not in the list, print the corresponding message.

Output:

3 在列表中

Document 对象参考手册Python3 Examples

Other Extensions