How to check if element is in list python

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?

How to check if element is in list python

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, else it returns false.

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 if block is executed. If ‘b’ was not present in MyList the else block would have been executed.

2. Using “not in” Operator

In this example, we are using a “not in” operator to check if an item or element exists in the list or not. If the element does not exist in the list it will return true else false.

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 'a' exists in the list or not if 'a' not in MyList : print(" item 'a' is not present in the list") else: print(" 'a' is present in the list")

Output:

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

Execution Time: 0.0009 (Seconds)

Explanation:
In the above example, we used the ‘not in’ operator to check whether ‘a’ exists in MyList or not. We used the if-else condition to print the result. The not in operator checks for if ‘a’ was not in the MyList. Since it is present in the list, the else block is executed. If ‘a’ was not present in MyList the if block would have been executed.

3. Using list.count() function

list.count(x)

We use count() function to count ‘x’ item in the list and returns the occurrence count of ‘x’ item in the list. If the occurrence count is greater than 0, it means ‘x’ item exists in the list.

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 'g' exists in the list or not using count() if MyList.count('g') > 0 : print(" 'g' is present in the list") else: print(" 'g' is not present in the list")

Output:

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

Execution Time: 0.0019 (Seconds)

Explanation:
In the above example we used the count() function. This function returns the no. of time an object occurs in a sequence. In this case ‘g’ does not occur even a single time thus, else block is executed.

Finding an item in a sequence without using any in-built function. The code is discussed briefly in the explanation section.

Example:

# Python3 code # Check if element or number exists in the list # Using for loop and if statement # Initialization of list MyList = ['a','b','c','d','e'] # Initialization a Flag variable Counter=0 # print list print("Our List: ", MyList) # Run for loop for i in MyList: if(i == 'a') : # If found initialize valuefound to 1 Counter=1 # Check if "valuefound" variable is set to 1 if(Counter== 1) : print(" 'a' is present in the List") else: print(" 'a' is not present in the List")

Output:

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

Execution Time: 0.0009 (Seconds)

Explanation:

In the above code, we used the for loop for iterating over the sequence i.e ‘MyList’. Then inside the for loop we used a if block which checks for every value of ‘i’ whether the item exists in the list or not. If it exists the if block sets the value of ‘counter’ to 1.

Outside the for loop we again used the if-else block to check for the value of ‘counter’. If counter value is 1 then if block is executed or else, else block is executed.    

The original question was:

What is the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is?

Thus there are two things to find:

  1. is an item in the list, and
  2. what is the index (if in the list).

Towards this, I modified @xslittlegrass code to compute indexes in all cases, and added an additional method.

Results

How to check if element is in list python

Methods are:

  1. in--basically if x in b: return b.index(x)
  2. try--try/catch on b.index(x) (skips having to check if x in b)
  3. set--basically if x in set(b): return b.index(x)
  4. bisect--sort b with its index, binary search for x in sorted(b). Note mod from @xslittlegrass who returns the index in the sorted b, rather than the original b)
  5. reverse--form a reverse lookup dictionary d for b; then d[x] provides the index of x.

Results show that method 5 is the fastest.

Interestingly the try and the set methods are equivalent in time.

Test Code

import random import bisect import matplotlib.pyplot as plt import math import timeit import itertools def wrapper(func, *args, **kwargs): " Use to produced 0 argument function for call it" # Reference https://www.pythoncentral.io/time-a-python-function/ def wrapped(): return func(*args, **kwargs) return wrapped def method_in(a,b,c): for i,x in enumerate(a): if x in b: c[i] = b.index(x) else: c[i] = -1 return c def method_try(a,b,c): for i, x in enumerate(a): try: c[i] = b.index(x) except ValueError: c[i] = -1 def method_set_in(a,b,c): s = set(b) for i,x in enumerate(a): if x in s: c[i] = b.index(x) else: c[i] = -1 return c def method_bisect(a,b,c): " Finds indexes using bisection " # Create a sorted b with its index bsorted = sorted([(x, i) for i, x in enumerate(b)], key = lambda t: t[0]) for i,x in enumerate(a): index = bisect.bisect_left(bsorted,(x, )) c[i] = -1 if index < len(a): if x == bsorted[index][0]: c[i] = bsorted[index][1] # index in the b array return c def method_reverse_lookup(a, b, c): reverse_lookup = {x:i for i, x in enumerate(b)} for i, x in enumerate(a): c[i] = reverse_lookup.get(x, -1) return c def profile(): Nls = [x for x in range(1000,20000,1000)] number_iterations = 10 methods = [method_in, method_try, method_set_in, method_bisect, method_reverse_lookup] time_methods = [[] for _ in range(len(methods))] for N in Nls: a = [x for x in range(0,N)] random.shuffle(a) b = [x for x in range(0,N)] random.shuffle(b) c = [0 for x in range(0,N)] for i, func in enumerate(methods): wrapped = wrapper(func, a, b, c) time_methods[i].append(math.log(timeit.timeit(wrapped, number=number_iterations))) markers = itertools.cycle(('o', '+', '.', '>', '2')) colors = itertools.cycle(('r', 'b', 'g', 'y', 'c')) labels = itertools.cycle(('in', 'try', 'set', 'bisect', 'reverse')) for i in range(len(time_methods)): plt.plot(Nls,time_methods[i],marker = next(markers),color=next(colors),linestyle='-',label=next(labels)) plt.xlabel('list size', fontsize=18) plt.ylabel('log(time)', fontsize=18) plt.legend(loc = 'upper left') plt.show() profile()

In this article we will discuss different ways to check if a given element exists in list or not.

Suppose we have a list of strings i.e.

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from']
Now let’s check if given list contains a string element ‘at’ ,

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)

Check if element exist in list using list.count() function

list.count(elem)
count(element) function returns the occurrence count of given element in the list. If its greater than 0, it means given element exists in list.
''' check if element exist in list using count() function ''' if listOfStrings.count('at') > 0 : print("Yes, 'at' found in List : " , listOfStrings)

Check if element exist in list based on custom logic

Python any() function checks if any Element of given Iterable is True.

Let’s use it to check if any string element in list is of length 5 i.e.

''' check if element exist in list based on custom logic Check if any string with length 5 exist in List ''' result = any(len(elem) == 5 for elem in listOfStrings) if result: print("Yes, string element with size 5 found") Instead of condition we can use separate function in any to match the condition i.e.

def checkIfMatch(elem): if len(elem) == 5: return True; else : return False; ''' Check if any string that satisfies the condition in checkIfMatch() function exist in List ''' result = any(checkIfMatch for elem in listOfStrings)
Complete example is as follows,
def checkIfMatch(elem): if len(elem) == 5: return True; else : return False; def main(): # List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # Print the List print(listOfStrings) ''' check if element exist in list using 'in' ''' if 'at' in listOfStrings : print("Yes, 'at' found in List : " , listOfStrings) ''' check if element NOT exist in list using 'in' ''' if 'time' not in listOfStrings : print("Yes, 'time' NOT found in List : " , listOfStrings) ''' check if element exist in list using count() function ''' if listOfStrings.count('at') > 0 : print("Yes, 'at' found in List : " , listOfStrings) ''' check if element exist in list based on custom logic Check if any string with length 5 exist in List ''' result = any(len(elem) == 5 for elem in listOfStrings) if result: print("Yes, string element with size 5 found") ''' Check if any string that satisfies the condition in checkIfMatch() function exist in List ''' result = any(checkIfMatch for elem in listOfStrings) if result: print("Yes, string element with size 5 found") if __name__ == '__main__': main()
Output:
['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, 'at' found in List : ['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, 'time' NOT found in List : ['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, 'at' found in List : ['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, string element with size 5 found Yes, string element with size 5 found