In order to check if an item exists in a list using python, we can use the 'in' keyword. This keyword will return a boolean value, True if the item exists in the list, and False if it does not. We can use this boolean value to control the flow of our program.
item in list
# create a list my_list = [20, 30, 50, 10, 80, 70, 40] # check if 80 exist inside the list if 80 in my_list: print("Item exists") else: print("Item does not exist")
You can also enclose the above code in a function to check if item exists in a list for one or multiple items.
def is_item_exist(my_list, item): if item in my_list: return True else: return False # test for mulltiple items nums = [1, 2, 3, 4, 5, 6] print(is_item_exist(nums, 4)) # -> True print(is_item_exist(nums, 9)) # -> False
In Python, you can check if an item exists in a list using the python For loop. To do this, you need to create a for loop that iterates through the list and checks if the item is in the list. If the item is in the list, we will print the message that the item exists.
fruits = ["Mango", "Orange", "Banana", "Grapes", "Papaya"] for item in fruits: if item == "Banana": print("Item exists") break else: print("Item not found")
Above is a for loop that iterates through a list of fruits. If the item being iterated over is equal to "Banana", the loop will break and print "Item exists". If the loop finishes iterating over the list without finding "Banana", it will print "Item not found".
List.count() is a function that returns the number of times an element appears in a list. This can be used to check if an element exists in a list. We will find the count of the specific item inside the list and if the count is greater than 0 then the item exists in the list and if it is equal to 0 then the item does not exist in the list.
Code example 1
fruits = ["Mango", "Orange", "Banana", "Grapes", "Papaya"] grape_count = fruits.count("Grapes") if grape_count > 0: print("Item exists") else: print("Item does not exist") # -> Item exists
Code example 2
apple_count = fruits.count("Apple") if apple_count > 0: print("Item exists") else: print("Item does not exist") # -> Item does not exist