Python | Ways to check if an item exists in a list



A list is an important container in Python, as if it stores items of all data types as a collection. Knowledge of certain list operations is essential for daytime programming. This article discusses one of the basic list operations, which allows you to check if an item is in the list.

Method 1: Naive method

In the “ Naive ”it is easy to use a loop that iterates over all the elements to check for the existence of the target element. This is the easiest way to check if an item is in the list.

Method 2: Using in

Python in — this is the most common way to check if an item exists in the list or not. This particular way returns True if the item exists in the list and False if the item does not exist in the list. The list does not need to be sorted to practice this validation approach.

Code # 1: Demo to check if an item is in a list using Naive method and in

# Python code for demonstration
# check if element exists
# using loops and in

 
# Initializing list

test_list = [ 1 , 6 , 3 , 5 , 3 , 4 ]

 

print ( "Checking if 4 exists in list (using loop):" )

 
# Check if 4 in the list
# using a loop

for i in test_list:

  if (i = = 4 ):

  print ( "Element Exists" )

  

print ( " Checking if 4 exists in list (using in): " )

  
# Check for 4 in the list
# use 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 a list to a set and then using in may be more efficient than using in . But having efficiency for plus also has certain disadvantages. One is that the order of the list is not preserved, and if you decide to take a new list for it, you will need to use the extra space. Another disadvantage is that the set disallows duplication, and therefore duplicate elements will be removed from the original list.

Method 4: Using sort () + bisect_left ()

The usual binary search way to check for the existence of an element, so the list must be sorted first and hence , do not preserve the order of the elements.  lower_bound () in C ++ STL.

Code # 2: Demo for checking if an item exists in a list using set () + in and sort () + bisect_left () .

# Python code for demonstration
# check existence element
# using set () + in
# using sort () + bisect_left ()

from bisect import bisect _left 

 
# 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):" )

  
# Check if 4 is in the 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 ()):" )

 
# Check for 4 in the list
# using sort () + bisect_left ()
test_list_bisect.sort ()

if bisect_left (test_list_bisect, 4 ):

print ( "Element Exists" )