python

Check if item exists in a list using python

Python is a programming language with many features and functions. One such function is the ability to check if an item exists in a list. In this post we will explain multiple methods that can be used to check whether an element exists in a list or not.

Check if item exists in a list using 'in' keyword

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.

Syntax

item in list

Code Example

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

Output

Item exists
  1. This code creates a list called my_list.
  2. It then checks if the number 80 is in the list using the python 'in' keyword.
  3. If it is, it prints "Item exists". If it is not, it prints "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

Check if item exists in a list using For Loop

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

Output

Item exists

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".

Use List.count() function to check if an element exists in a list

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
Was this helpful?