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

Python Check Whether an Element Exists in a List

Python Check Whether an Element Exists in a List

Document Object Reference Manual Python3 Examples

Define a list and check whether an element is in it.

Example 1

test_list

=

[

1

,

6

,

3

,

5

,

3

,

4

]

 

print

(

"Check whether 4 is in the list (using a loop) : "

)

 

for

i

in

test_list:

   

if

(

i

==

4

)

:

       

print

(

"exists"

)

 

print

(

"Check whether 4 is in the list (using the in keyword) : "

)

if

(

4

in

test_list

)

:

   

print

(

"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

]

 

print

(

"Check whether 4 is in the list (using set() + in) : "

)

 

test_list_set

=

set

(

test_list_set

)

if

4

in

test_list_set :

   

print

(

"exists"

)

 

print

(

"Check whether 4 is in the list (using count()) : "

)

 

if

test_list_bisect.

count

(

4

)

0

:

   

print

(

"exists"

)

The output of the above example is:



查看 4 是否在列表中 ( 使用 set() + in) : 

存在

查看 4 是否在列表中 ( 使用 count()) : 

存在

Document Object Reference Manual Python3 Examples