Easy Tutorial
❮ Python Os Close Python Os Chown ❯

Python Check if Element Exists in List

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 exists in the list (using a loop): ") 
  
for i in test_list: 
    if(i == 4) : 
        print ("Exists") 
  
print("Check if 4 exists in the list (using the in keyword): ") 

if (4 in test_list): 
    print ("Exists")

The output of the above example is:

Check if 4 exists in the list (using a loop): 
Exists
Check if 4 exists in the list (using the in keyword): 
Exists

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 exists 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 exists in the list (using count()): ") 
  
if test_list_bisect.count(4) > 0 :
    print ("Exists")

The output of the above example is:

Check if 4 exists in the list (using set() + in): 
Exists
Check if 4 exists in the list (using count()): 
Exists

Python3 Examples

❮ Python Os Close Python Os Chown ❯