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

Python checking whether a list contains a specific element

Python checking whether a list contains a specific element

Document Object Reference Manual Python3 Examples

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:

   

print

(

f

"{element} exists in the list"

)

else

:

   

print

(

f

"{element} does not exist in the list"

)

Code analysis:

  1. my_list is a list containing integers 1 to 5.
  2. element is the element we want to check for existence in the list, set to 3 here.
  3. if element in my_list: This line of code uses in keyword to check element whether my_list it.
  4. If both the element exists in my_list , it prints "{element} 存在于列表中", otherwise it prints "{element} 不存在于列表中"。

Output result:

3 存在于列表中

Document Object Reference Manual Python3 Examples