Write a Python program to search whether a given element is present in a list or not

Check if element exists in list in Python

List is an important container in python as if stores elements of all the datatypes as a collection. Knowledge of certain list operations is necessary for day-day programming. This article discusses one of the basic list operations of ways to check the existence of elements in the list.

Method 1: Naive Method

In Naive method, one easily uses a loop that iterates through all the elements to check the existence of the target element. This is the simplest way to check the existence of the element in the list.

Method 2: Using in

Python is the most conventional way to check if an element exists in a list or not. This particular way returns True if an element exists in the list and False if the element does not exist in the list. List need not be sorted to practice this approach of checking.

Code #1: Demonstrating to check the existence of an element in the list using the Naive method and in.




# Python code to demonstrate
# checking of element existence
# using loops and in
# Initializing list
test_list = [ 1, 6, 3, 5, 3, 4 ]
print("Checking if 4 exists in list ( using loop ) : ")
# Checking if 4 exists in list
# using loop
for i in test_list:
if(i == 4) :
print ("Element Exists")
print("Checking if 4 exists in list ( using in ) : ")
# Checking if 4 exists in list
# using in
if (4 in test_list):
print ("Element Exists")

Output :



Checking if 4 exists in list ( using loop ) : Element Exists Checking if 4 exists in list ( using in ) : Element Exists

Method 3 : Using set() + in

Converting the list into the set and then using in can possibly be more efficient than only using in. But having efficiency for a plus also has certain negatives. One among them is that the order of list is not preserved, and if you opt to take a new list for it, you would require to use extra space. Another drawback is that set disallows duplicity and hence duplicate elements would be removed from the original list.

Method 4 : Using sort() + bisect_left()

The conventional binary search way of testing element existence, hence list has to be sorted first and hence not preserving the element ordering. bisect_left() returns the first occurrence of the element to be found and has worked similarly to lower_bound() in C++ STL.

Note: The bisect function will only state the position of where to insert the element but not the details about if the element is present or not.

Code #2 : Demonstrating to check existence of element in list using set() + in and sort() + bisect_left().




# Python code to demonstrate
# checking of element existence
# using set() + in
# using sort() + bisect_left()
from bisect import bisect_left ,bisect
# Initializing list
test_list_set = [ 1, 6, 3, 5, 3, 4 ]
test_list_bisect = [ 1, 6, 3, 5, 3, 4 ]
print("Checking if 4 exists in list ( using set() + in) : ")
# Checking if 4 exists in list
# using set() + in
test_list_set = set(test_list_set)
if 4 in test_list_set :
print ("Element Exists")
print("Checking if 4 exists in list ( using sort() + bisect_left() ) : ")
# Checking if 4 exists in list
# using sort() + bisect_left()
test_list_bisect.sort()
if bisect_left(test_list_bisect, 4)!=bisect(test_list_bisect, 4):
print ("Element Exists")
else:
print("Element doesnt exist")

Method 5 : Using count()

We can use the in-built python List method, count(), to check if the passed element exists in List. If the passed element exists in the List, count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.

Code #3 : Demonstrating to check the existence of elements in the list using count().




"""
Python code to demonstrate
checking of element existence
using List count() method
"""
# Initializing list
test_list = [10, 15, 20, 7, 46, 2808]
print("Checking if 15 exists in list")
# number of times element exists in list
exist_count = test_list.count(15)
# checking if it is more then 0
if exist_count > 0:
print("Yes, 15 exists in list")
else:
print("No, 15 does not exists in list")

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




Article Tags :
Python
Python list-programs
python-list
Practice Tags :
python-list

Python: Check if Element Exists in List

In python, list is a collections of data-types, which is used to store all the data types. In this tutorial we will learn in python, how to check if an item, element, number, value, object, word exists in the list?

Write a Python program to search whether a given element is present in a list or not

1. Using “in” Operator

In this example, we are using ‘in’ operator to check if an item or element exists in a sequence or not. If an item exists in the list, it will return the output is true, elseit returnsfalse.

Example:

# Python3 code # Check if element exists in the list # Using in Operator # Initialization of list MyList = ['a','b','c','d','e'] # Print list print("Our List: ", MyList) # Check if 'b' exists in the list or not if 'b' in MyList: print(" Item 'b' is present in the list") else: Print(" Item 'b' is not present in the list")

Output:

Our List:['a','b','c','d','e'] Item 'b' is present in the list

Execution Time: 0.0009 (Seconds)

Explanation:

In the above example, we used the ‘in’ operator to check whether ‘b’ exists in MyList or not. We used the if-else condition to print the result. Since ‘b’ is present in the list, the ifblock is executed. If ‘b’ was not present in MyList the elseblock would have been executed.

Python Program to check if element exists in list

In this tutorial, we will learn how to check if an element is present in a list or not. List is an ordered set of values enclosed in square brackets [ ]. List stores some values called elements in it, which can be accessed by their particular index. We will be discussing the various approaches by which we can check for an element in the given list.

The program will accept the list and the element which has to check, it should return True if it exists else, it will return False

Input: [6, 22, 7, 3, 0, 11] element= 0

Output: True

Let us look at the different approaches we can follow to execute the task.

Python program to check if an element is present in list

Here, we will write a Python program to check whether the specified element is present in the list or not.
Submitted by Shivang Yadav, on April 06, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered sets of values enclosed in square brackets [].

Check if an element is present in the list

We will take a list as input from the user and then ask the user to enter the element's value to be searched. Then we will return YES/NO based on whether the element is present in the list or not.

Example:

Input: [4, 2, 9, 5, 1, 0, 7] element -> 5 Output: Present

Python provides us multiple ways to perform the tasks. And to check for an element's presence also, we can use multiple ways in which the present can be check.

Method 1: Searching technique

To check whether an element is present in a list or not. We can simply use any searching technique and find the element in the list.

Here, we will discept linear search.

  • loop through the list
    • if : list[i] == element
    • found = true
    • break
  • if : found == true
    • print "found"
  • else : print "not found"

Program to check if an element is present in the list

# Python program to check if an # element exists in list # Getting list from user myList = [] length = int(input("Enter number of elements: ")) for i in range(0, length): value = int(input()) myList.append(value) ele = int(input("Enter element to be searched in the list: ")) # checking for the presence of element in list found = False for i in myList: if(i == ele) : found = True break if(found): print("Element found") else : print("Element not found!")

Output:

Enter number of elements: 5 2 6 8 4 1 Enter element to be searched in the list: 4 Element found

Method 2: Using in operator

Python programming language provides us an operator "in" to check whether an element is present in a list.

Syntax:

Returns boolean values based on the presence of element in the list.

Algorithm:

  • Get the list and seach_element from the user.
  • Check if the element is present in list using in
    • if seach_element in list
      • Print "element found"

Program to check if an element is present in a list using in operator

# Python program to check if an element # exists in list # Getting list from user myList = [] length = int(input("Enter number of elements: ")) for i in range(0, length): value = int(input()) myList.append(value) ele = int(input("Enter element to be searched in the list: ")) # checking for the presence of element in list if(ele in myList): print("Element found") else : print("Element not found!")

Output:

Enter number of elements: 5 10 20 30 40 50 Enter element to be searched in the list: 30 Element found

Method 3: Using bisect_left() method on sorted list

The list needs to be sorted in order to apply this method.

The bisect_left() method find's and returns the first occurrence of the given element in a sorted array.

Syntax:

For sorting list list_name.sort() bisect_left method : bisect_left(list, element)

Returns a boolean value based on whether the element is present in the list or not.

Program to check if an element is present in list

# Python program to check if an element # exists in list import bisect # Getting list from user myList = [] length = int(input("Enter number of elements: ")) for i in range(0, length): value = int(input()) myList.append(value) ele = int(input("Enter element to be searched in the list: ")) # checking for the presence of element in list myList.sort() if(bisect.bisect_left(myList, ele) ): print("Element found") else : print("Element not found!")

Output:

Enter number of elements: 5 10 12 15 20 25 Enter element to be searched in the list: 25 Element found

Python List Programs »


How to find the length of a list in Python (3 effective ways)?
Python program to swap any two elements in the list

ADVERTISEMENT


Preparation


Aptitude Questions MCQs Find Output Programs

What's New

  • MongoDB MCQs
  • Java MCQs
  • C# MCQs
  • Scala MCQs
  • Blockchain MCQs
  • AutoCAD MCQs
  • PHP MCQs
  • JavaScript MCQs
  • jQuery MCQs
  • ReactJS MCQs
  • AngularJS MCQs
  • JSON MCQs
  • Ajax MCQs
  • SASS MCQs
  • HTML MCQs
  • Advanced CSS MCQs
  • CSS MCQs
  • PL/SQL MCQs
  • SQL MCQs
  • MS Word MCQs
  • PL/SQL MCQs
  • SQL MCQs
  • Software Engineering MCQs
  • MIS MCQs
  • Generally Accepted Accounting Principles MCQs
  • Bills of Exchange MCQs
  • Business Environment MCQs
  • Sustainable Development MCQs
  • Marginal Costing and Absorption Costing MCQs
  • Globalisation MCQs
  • Indian Economy MCQs
  • Retained Earnings MCQs
  • Depreciation MCQs
  • Partnership MCQs
  • Sole Proprietorship MCQs
  • Goods and Services Tax (GST) MCQs
  • Cooperative Society MCQs
  • Capital Market MCQs
  • Business Studies MCQs
  • Basic Accounting MCQs
  • MIS Executive Interview Questions
  • Go Language Interview Questions
ADVERTISEMENT

Top Interview Coding Problems/Challenges!

  • Run-length encoding (find/print frequency of letters in a string)
  • Sort an array of 0's, 1's and 2's in linear time complexity
  • Checking Anagrams (check whether two string is anagrams or not)
  • Relative sorting algorithm
  • Finding subarray with given sum
  • Find the level in a binary tree with given sum K
  • Check whether a Binary Tree is BST (Binary Search Tree) or not
  • 1[0]1 Pattern Count
  • Capitalize first and last letter of each word in a line
  • Print vertical sum of a binary tree
  • Print Boundary Sum of a Binary Tree
  • Reverse a single linked list
  • Greedy Strategy to solve major algorithm problems
  • Job sequencing problem
  • Root to leaf Path Sum
  • Exit Point in a Matrix
  • Find length of loop in a linked list
  • Toppers of Class
  • Print All Nodes that don't have Sibling
  • Transform to Sum Tree
  • Shortest Source to Destination Path

Comments and Discussions!



Please enable JavaScript to view the comments powered by Disqus.
ADVERTISEMENT

Python List Contains: How to Check If Item Exists in List

During development in Machine learning, AI, or even web development, we generally come across a problem where we need to test if the particular item from a given list lies as a sub-string or not. To check if the list contains the specific element or not in Python, use the“in”operator or“not in” operator. Let’s explore this topic in detail.

Check if element exists in list using python “in” Operator

Condition to check if element is in List :

elem in LIST
It will return True, if element exists in list else return false.

For example check if ‘at’ exists in list i.e.

''' check if element exist in list using 'in' ''' if 'at' in listOfStrings : print("Yes, 'at' found in List : " , listOfStrings)
Condition to check if element is not in List :
''' check if element NOT exist in list using 'in' ''' if 'time' not in listOfStrings : print("Yes, 'time' NOT found in List : " , listOfStrings)
Advertisements

Python Program to Search an Element in a List



This article deals with some programs in Python that searches an element in a list. Here both element and list must be entered by user at run-time. Here are the list of programs covered in this article:

  • Search an element in a list of 5 elements
  • Search an element in a list of n elements
  • Check if a value exists in a given list, using in operator

Python Check If List Item Exists

❮ Python Glossary

Check If List Item Exists

To determine if a specified item is present in a list use the in keyword:

Example

Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Try it Yourself »