Python List Contains: How to Check If Item Exists in List

During machine learning, AI, or even web development, we generally encounter a problem where we need to check if the specific item from a given list lies as a sub-string.

This article will explore different ways to check if a list contains a specific item.

Python list contains

5 easy ways to check if a list contains an element in Python.

  1. Using the “in” operator
  2. Using list comprehension
  3. Using list.count() method
  4. Using any() function
  5. Using the “not in” operator

Method 1: Using the “in” operator

To check if the list contains an element in Python, use the “in” operator. The “in” operator checks whether the list contains a specific item. It can also check if the element exists on the list using the list.count() function.

Python list is an essential container as it stores elements of all the data types as a collection. The “in operator” is the most convenient way to check whether an item exists on the list.

This approach returns True if an item exists in the list and False if an item does not exist. The list need not be sorted to practice this approach of checking.

Checking if the item exists in the list

To check if an item exists in the list, use the “in operator”. Then, use the “in” operator with the if condition, and if the item exists in the list, then the condition returns True, and if not, it returns False.

Syntax

item in List

Return Value

It will return True if an item exists in the list else returns False.

# app.py

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

if 'S Eductation' in listA:
    print("Yes, 'S Eductation' found in List : ", listA)

Output

python3 app.py
Yes, 'S Eductation' found in List :  ['Stranger Things', 'S Education', 'Game of Thrones']

Let’s take an example where we do not find an item on the list.

# app.py

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

if 'Dark' in listA:
    print("Yes, 'S Eductation' found in List : ", listA)
else:
    print("Nope, 'Dark' not found in the list")

Output

python3 app.py
Nope, 'Dark' Not found in the list

The list does not contain the dark element, so it returns False, and the else block executes.

Method 2: Using List comprehension

Use list comprehension to check if a list contains single or multiple elements in Python.

main_list = [11, 21, 19, 18, 46]
check_elements = [11, 19, 46]

if all([item in main_list for item in check_elements]):
  print("The list contains all the items")

Output

The list contains all the items

In this example, we defined two lists.

  1. The main_list is our primary list which we will check for multiple elements.
  2. The check_elements list contains elements we will check in the main_list.

Using list comprehension, we are checking if all the elements of check_list are present in the main_list.

In our case, It returns True since all the elements are present. That’s why if condition is executed.

Example 2

# app.py

data_string = "The last season of Game of Thrones was not good"

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

print("The original string : " + data_string)

print("The original list : " + str(listA))

res = [ele for ele in listA if(ele in data_string)]

print("Does string contain any list element : " + str(bool(res)))

Output

python3 app.py

The original string : The last season of Game of Thrones was not good
The original list : ['Stranger Things', 'S Education', 'Game of Thrones']
Does string contain any list element : True

List comprehensions provide a concise way to create lists.

It consists of brackets containing the expression followed by a for clause, then zero or more for or if clauses. The expressions can be anything, meaning you can put all objects in lists.

The result will be the new list resulting from evaluating an expression in the context of the for and if clauses follow it.

In our example, we check for the list and also with string items if we can find a match and return true.

Let’s see if the string contains the word which does not exist in an item of the list.

# app.py

data_string = "The last season of BoJack Horseman was good"

# initializing test list
listA = ['Stranger Things', 'S Education', 'Game of Thrones']

# printing original string
print("The original string : " + data_string)

# printing original list
print("The original list : " + str(listA))

# using list comprehension
# checking if string contains list element
res = [ele for ele in listA if(ele in data_string)]

# print result
print("Does string contain any list element : " + str(bool(res)))

Output

python3 app.py
The original string: The last season of BoJack Horseman was good
The original list : ['Stranger Things', 'S Education', 'Game of Thrones']
Does string contain any list element: False

Method 3: Using the list.count() function

To check if the item exists in the Python list, use the list.count() method.

Syntax

list.count(elem)

The List count(item) method returns the occurrence count of the given element in the list. If it’s greater than 0, a given item exists in the list.

# app.py

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

if listA.count('Stranger Things') > 0:
    print("Yupp, 'Stranger Things' found in List : ", listA)

Output

python3 app.py
Yupp, 'Stranger Things' found in List :  ['Stranger Things', 'S Education', 'Game of Thrones']

Method 4: Using any() method

Python any() function is the most classical way to perform this task efficiently. The any() function checks for a match in a string with a match of each list element.

# app.py

data_string = "The last season of Game of Thrones was not good"

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

print("The original string : " + data_string)

print("The original list : " + str(listA))

res = any(item in data_string for item in listA)

print("Does string contain 'Game of Thrones' list element: " + str(res))

Output

python3 app.py
The original string : The last season of Game of Thrones was not good
The original list : ['Stranger Things', 'S Education', 'Game of Thrones']
Does string contain 'Game of Thrones' list element: True

From the output, Game of Thrones exists in the list.

Method 5: Use not in inverse operator.

Python “not in” is a built-in operator that evaluates to True if it does not find a variable in the specified sequence and False otherwise.

To check if the list contains a particular item, use the not in inverse operator.

listA = ['Stranger Things', 'S Education', 'Game of Thrones']
if 'Witcher' not in listA:
    print("Yes, 'Witcher' is not found in List : ", listA)

Output

python3 app.py
Yes, 'Witcher' is not found in List :  ['Stranger Things', 'S Education', 'Game of Thrones']

Python in and not in operators work fine for lists, tuples, sets, and dicts (check keys).

Python all() method to check if the list exists in another list

In this program, you will learn to check if the Python list contains another list’s items and display the result using the python print() function.

We will use two lists having overlapping values. One of these is the big one that holds all the items of the second one.

  1. List1 – List1 contains all or some of the items of another list.
  2. List2 – It is the subset of the first one.
# app.py

List1 = ['Homer',  'Bart', 'Lisa', 'Maggie', 'Lisa']

List2 = ['Bart', 'Homer', 'Lisa']

check = all(item in List1 for item in List2)

if check is True:
    print("The list {} contains all elements of the list {}".format(List1, List2))
else:
    print("No, List1 doesn't have all elements of the List2.")

Output

python3 app.py
The list ['Homer', 'Bart', 'Lisa', 'Maggie', 'Lisa'] contains all elements of the list ['Bart', 'Homer', 'Lisa']

You can see that the first list contains all the elements of the second list. This is because we have checked the first list using the all() method.

FAQ

How to check if a list contains a specific element in Python?

Use the “in operator” to check if an element exists in a list in Python.

Can I use the count() method to check if a list contains a specific item?

Yes, in Python, you can use the count() method to check if a list contains a specific item.

How to check if a list contains all items from another list in Python?

Use Python all() function and a generator expression to check if all items from another list exist in a list.

How do you check if a list contains any item from another list in Python?

Use the any() function and a generator expression to check if any items from another list exist in a list in Python.

How to check if a list contains duplicate elements in Python?

Use the len() function in combination with the set() function to check if the number of unique items in a list is less than the number of items in the list in Python.

How to remove duplicate items from a list in Python?

Use the set() method to create a set of unique elements from a list and then convert it back to a list.

Conclusion

The best and most efficient way to check if a list contains an element is to use the “in operator” in Python.

1 thought on “Python List Contains: How to Check If Item Exists in List”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.