Python list contains
This article will explain 4 different ways to check if a python list contains a value or if an item exists in a list with example programs.
List may be of numbers, strings, floats etc.
Write the value that you want to find in the list followed by
in
operator and the list.The expression will be
True
if the list contains the element else it will be False
.Example,
# list of numbers l = [1, 45, 89, 56, 35, 78, 101] element = 56 if element in l: print(element,"found in list") else: print(element,"not present in list")
Above code will output
56 found in list
Method 2: Using count function
Python’s built-in count()
function is invoked on a list and accepts a single argument.
This function checks if the argument is present in the list.
It returns the number of occurrences of the argument in the list.
Thus, if the element does not exist in the list, it will return 0.
So, in order to test if the list contains an element, invoke count
with the value as argument and compare the return value with 0. Example,
Below program checks if a word is in a list of words.
# list of strings l = ['I', 'am', 'trying', 'to', 'search', 'value', 'in', 'list'] element = 'search' if l.count(element) > 0: print(element,"found in list") else: print(element,"not present in list")
This code will print
search found in list
This is the most primitive method to find an item in a list. Iterate over the list using a for loop and compare the current loop element with the item to search.
Don’t forget to break the loop once the item is found in the list to avoid unnecessary iterations.
Example,
# list of floats mean = [10.5, 20.67, 35.89, 60.42, 33.33] element = 34.5 found = False # iterate list for item in mean: # compare element with list item if item == element: found = True break if found: print(element,"found in list") else: print(element,"not present in list")
Above example will print
34.5 not present in list
Notice the use of boolean variable and break
statement.
Method 4: Using set() and in
Convert the list to a set using set()
function and then use in
operator to test if the element is present in the set.
Example,
# list of floats mean = [10.5, 20.67, 35.89, 60.42, 33.33] element = 34.5 # convert to set mean = set(mean) if element in mean: print(element,"found in list") else: print(element,"not present in list")
Above program will output
34.5 not present in list
Note that the set does not preserve the ordering of elements.
In case you want the elements in ordered positions, then you need to assign the set to a new variable which will require extra memory space.