Python checking whether a list contains a specific element
In Python, we can use in keyword to check whether a list contains a specific element.in keyword returns a boolean value; if the element exists in the list, it returns True; otherwise, returns False。
Example
my_list
=
[
1
,
2
,
3
,
4
,
5
]
element
=
3
if
element
in
my_list:
(
f
"{element} exists in the list"
)
else
:
(
f
"{element} does not exist in the list"
)
Code analysis:
my_listis a list containing integers 1 to 5.elementis the element we want to check for existence in the list, set to 3 here.if element in my_list:This line of code usesinkeyword to checkelementwhethermy_listit.- If both the
elementexists inmy_list, it prints"{element} 存在于列表中", otherwise it prints"{element} 不存在于列表中"。
Output result:
3 存在于列表中
Python3 Examples