Python Check Whether an Element Exists in a List
Define a list and check whether an element is in it.
Example 1
test_list
=
[
1
,
6
,
3
,
5
,
3
,
4
]
(
"Check whether 4 is in the list (using a loop) : "
)
for
i
in
test_list:
if
(
i
==
4
)
:
(
"exists"
)
(
"Check whether 4 is in the list (using the in keyword) : "
)
if
(
4
in
test_list
)
:
(
"exists"
)
The output of the above example is:
查看 4 是否在列表中 ( 使用循环 ) :
存在
查看 4 是否在列表中 ( 使用 in 关键字 ) :
存在
Example 2
Initialize the list
test_list_set
=
[
1
,
6
,
3
,
5
,
3
,
4
]
test_list_bisect
=
[
1
,
6
,
3
,
5
,
3
,
4
]
(
"Check whether 4 is in the list (using set() + in) : "
)
test_list_set
=
set
(
test_list_set
)
if
4
in
test_list_set :
(
"exists"
)
(
"Check whether 4 is in the list (using count()) : "
)
if
test_list_bisect.
count
(
4
)
0
:
(
"exists"
)
The output of the above example is:
查看 4 是否在列表中 ( 使用 set() + in) :
存在
查看 4 是否在列表中 ( 使用 count()) :
存在
Python3 Examples