Python: Check if a list contains a specific element
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")
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:
my_listis a list containing the integers 1 to 5.elementis the element we want to check whether it exists in the list, set to 3 here.if element in my_list:This line of code uses theinkeyword to check whetherelementis inmy_list.- If
elementexists inmy_list, then print"{element} 存在于列表中"; otherwise, print"{element} 不存在于列表中"。
Output result:
3 存在于列表中Other extensions
Python3 Examples