Python: Check if Element Exists in List

Document 对象参考手册Python3 Examples

Define a list and check if an element exists in the list.

Example 1

test_list = [ 1, 6, 3, 5, 3, 4 ]
 
print("Check if 4 is in the list (using a loop): ")
 
for i in test_list:
    if(i == 4) :
        print ("Exists")
 
print("Check if 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 if 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 if 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 对象参考手册Python3 Examples

Other Extensions