How to Check If Elements Present in List in Python | Python Program

In this article, we will learn to check if an element exists in a list or not using the python program.

We find the existence of the elements in the list using three methods:

  1. By iterating the elements of the list
  2. Using in operators
  3. Using counter()


Iterating the elements of the list

Explanation

  1. First, we iterate the list and check the elements one by one. 
  2. And if elements is found then print elements exit otherwise print elements don't exist.

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# list 
list = ['a', 'b', 'c', 'h', 'w', 'z']
element = 'c' # element to search in list

# set flag vaiable to True
flag = True

# iterate the list
for i in list:
    # check the element is exits or not
    if element == i:
        # if it exit then flag = True
        flag = True  
        break
    else:
        # if element not exits then set flag = False
        flag = False
        
# Print the results
if flag == True:
    print("This",element,"elements exits in list")
else:
    print("This",element,"elements doesn't exits in list")

Output

This c elements exits in list


Using in operator

Explanation

  1. Using in operator we can check whether the elements exist in the list or not.
  2. And if elements is found then print elements exit otherwise print elements don't exist.

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# list 
list = ['a', 'b', 'c', 'h', 'w', 'z']
element = 'c' # element to search in list

# check the elements exits in list using in operators
if element in list:
    # if elements exits 
    print("This",element,"elements exits in list")
else:
    # if elements doesn't exits 
    print("This",element,"elements doesn't exits in list")

Output

This c elements exits in list


Using count()

Explanation

  1. The count () function is used to count the occurrence of elements in the list.
  2. So, we count the occurrence of elements that we have to search, if it is more than 0 then the elements exist in the list.
  3. And if elements is found then print elements exit otherwise print elements don't exist.

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# list 
list = ['a', 'b', 'c', 'h', 'w', 'z']
element = 'p' # element to search in list

# check the elements exits in list using in operators
if list.count(element) > 0:
    # if elements exits 
    print("This",element,"elements exits in list")
else:
    # if elements doesn't exits 
    print("This",element,"elements doesn't exits in list")

Output

This p elements doesnt exits in list
Next Post Previous Post
No Comment
Add Comment
comment url