Python: Check if a list contains a specific element

Document 对象参考手册Python3 Examples

In Python, we can use theinkeyword to check if a list contains a specific element.inThe keyword returns a boolean value. If the element exists in the list, it returnsTrue, otherwise it returnsFalse。

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 explanation:

  1. my_listis a list containing the integers 1 to 5.
  2. elementis the element we want to check whether it exists in the list, set to 3 here.
  3. if element in my_list:This line of code uses theinkeyword to check whetherelementis inmy_list.
  4. Ifelementexists inmy_list, then print"{element} 存在于列表中"; otherwise, print"{element} 不存在于列表中"。

Output result:

3 存在于列表中

Document 对象参考手册Python3 Examples

Other extensions