Javaexercise.com

Python Program to Find an Element in Python List

To find an element in a list, python provides several built-in ways such as in operator, count() function, and index() function. Apart from that, we will use custom code as well to find an element. We will learn to use all these in our examples to find an element in the list. So, let's get started.

 

Find an element in Python List

This is an iterative approach where we use a loop to traverse each element of the list and then check via an if statement. If the element is matched, then display found message else, display not found. See the below python code.

# Python program to find an element in a list

# Take a list
list1 = [45, 11, 15, 9, 56, 17]
print(list1)

val = 15
flag = 0
for i in list1:
  if i == val:
    flag = 1
  
if flag:
  print("Element exists")
else: 
  print("Element does not exist")

Output:

Element exists

 

Find an element in List by using the count() method in Python

We can use the count() method to check whether the element is present in the list or not. The count() method returns the frequency of an element in the list. So, if the count is greater than 0 then it means the element is present in the list. See the python code.

# Python program to find an element in a list

# Take a list
list1 = [45, 11, 15, 9, 56, 17]
print(list1)

val = 15 # Element to find

# Count method returns frequency of a number
result = list1.count(val)

if result:
  print("Element exists")
else: 
  print("Element does not exist")

Output:

Element exists

 

Find an element in List by using an in operator in Python

We can use an in operator to check whether the specified element is present in a list. It is a membership operator that works for all iterable like list, set, tuple, etc. See the python code.

# Python program to find an element in a list

# Take a list
list1 = [45, 11, 15, 9, 56, 17]
print(list1)

val = 15

# Python in operator
if val in list1:
  print("Element exists")
else: 
  print("Element does not exist")

Output:

Element exists

 

Find an element in List by using index() Method in Python

Python index() method is used to find the index value of an element in the iterable(list, set, tuple, etc). We can use it to find an element in the list. This method returns an error if the element is not found, then you should use it with the try-catch statement. See the python code.

# Python program to find an element in a list

# Take a list
list1 = [45, 11, 15, 9, 56, 17]
print(list1)

val = 15

try:
    result = list1.index(val)
except ValueError:
  print("Element does not exist")
else: 
  print("Element exists") 

Output:

Element exists

 

if you don't use the try-catch statement with the index() method then it throws an error :

result = list1.index(111)

ValueError: 111 is not in list