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:
- By iterating the elements of the list
- Using in operators
- Using counter()
Iterating the elements of the list
Explanation
- First, we iterate the list and check the elements one by one.
- 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
- Using in operator we can check whether the elements exist in the list or not.
- 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
- The count () function is used to count the occurrence of elements in the list.
- 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.
- 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