Python Check Whether a Number Is in a List
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:
(
f
"{num_to_check} is in the list"
)
else
:
(
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:: When usinginkeyword checknum_to_checkwhethernumberslist.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, executeelseblock is executed.print(f"{num_to_check} 不在列表中"): If the number is not in the list, print the corresponding message.
Output result:
3 在列表中
Python3 Examples