Python: Check if Element Exists in List
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")
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")
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()) : 存在Other Extensions
Python3 Examples