Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Check Whether a Number Is in a List

Python Check Whether a Number Is in a List

Document Object Reference Manual Python3 Examples

We can use Python's in keyword to check whether a number exists in a list.in keyword returns a boolean value; if the number is in the list, it returns True; otherwise, returns False。

Example

Define a list

numbers

=

[

1

,

2

,

3

,

4

,

5

]

The number to check

num_to_check

=

3

Check whether 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:: When using in keyword check num_to_check whether numbers 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, execute else block is executed.
  6. print(f"{num_to_check} 不在列表中"): If the number is not in the list, print the corresponding message.

Output result:

3 在列表中

Document Object Reference Manual Python3 Examples