Check if an item exists in a list in Python

You have a list, and you want to check whether an element you have is already present inside the list. There are a few ways you can do it in Python.

A quick way to check if an item is inside a list

  1. Create a variable with the value you want to check.
myvar = 'just'
  1. Create a list of items.
mylist = ['This', 'is', 'just', 'a', 'text', 'string']
  1. Use the IF condition to check the value.
if myvar in mylist:
  1. Use ELSE to execute a message if the value is not present in the list.

The full example is going to look like this:

mylist = ['This', 'is', 'just', 'a', 'text', 'string']

myvar = 'just'

if myvar in mylist:
    print('The value exists.')
else:
    print('The value does not exist.')

Alternative version with the list.count() function

If you want to check not only whether the value exists in a list, but also how many times, you can use the list.count function.

mylist = ['This', 'is', 'just', 'a', 'text', 'string', 'just']

myvar = 'just'

if mylist.count(myvar) > 0:
    print('The number of values inside the list: ' + str(mylist.count(myvar)))
else:
    print('The value does not exist.')

Add value if unique in a list

In the next example, we are going to create a function that checks whether the value is not present inside a list.

If the value is present, then it means that the value is not unique and the function returns False, otherwise the value is unique, and function adds it to the list and returns True.

def add_unique(list, value):
    for element in list:
        if value in element:
            return False

    list.append(value)
    return True

mylist = ['This', 'is', 'just', 'a', 'text', 'string']

add_unique(mylist, ',')
add_unique(mylist, 'string')
add_unique(mylist, 'right')