How do i search for items in python that are not in another list?

TL;DR:
SOLUTION (1)

import numpy as np
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`

SOLUTION (2) You want a sorted list

def setdiff_sorted(array1,array2,assume_unique=False):
    ans = np.setdiff1d(array1,array2,assume_unique).tolist()
    if assume_unique:
        return sorted(ans)
    return ans
main_list = setdiff_sorted(list_2,list_1)

EXPLANATIONS:
(1) You can use NumPy's setdiff1d (array1,array2,assume_unique=False).

assume_unique asks the user IF the arrays ARE ALREADY UNIQUE.
If False, then the unique elements are determined first.
If True, the function will assume that the elements are already unique AND function will skip determining the unique elements.

This yields the unique values in array1 that are not in array2. assume_unique is False by default.

If you are concerned with the unique elements (based on the response of Chinny84), then simply use (where assume_unique=False => the default value):

import numpy as np
list_1 = ["a", "b", "c", "d", "e"]
list_2 = ["a", "f", "c", "m"] 
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`


(2) For those who want answers to be sorted, I've made a custom function:

import numpy as np
def setdiff_sorted(array1,array2,assume_unique=False):
    ans = np.setdiff1d(array1,array2,assume_unique).tolist()
    if assume_unique:
        return sorted(ans)
    return ans

To get the answer, run:

main_list = setdiff_sorted(list_2,list_1)

SIDE NOTES:
(a) Solution 2 (custom function setdiff_sorted) returns a list (compared to an array in solution 1).

(b) If you aren't sure if the elements are unique, just use the default setting of NumPy's setdiff1d in both solutions A and B. What can be an example of a complication? See note (c).

(c) Things will be different if either of the two lists is not unique.
Say list_2 is not unique: list2 = ["a", "f", "c", "m", "m"]. Keep list1 as is: list_1 = ["a", "b", "c", "d", "e"]
Setting the default value of assume_unique yields ["f", "m"] (in both solutions). HOWEVER, if you set assume_unique=True, both solutions give ["f", "m", "m"]. Why? This is because the user ASSUMED that the elements are unique). Hence, IT IS BETTER TO KEEP assume_unique to its default value. Note that both answers are sorted.

pythonnumpy

During development in Machine learning, AI, or even web development, we generally come across a problem where we need to test if the particular item from a given list lies as a sub-string or not. To check if the list contains the specific element or not in Python, use the “in” operator or “not in” operator. Let’s explore this topic in detail.

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

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

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.

To check if the item exists in the list, use Python “in operator”. For example, we can use the “in” operator with the if condition, and if the item exists in the list, then the condition returns True, and if not, then it returns False.

See the following syntax of Python in operator.

# 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 in which 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 else block executes.

Check item exists in the list using List comprehension.

We can also use list comprehension to check if the item exists in the Python list.

See the following code.

# 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 the 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 types of 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

Check if an element exists in the list using the list.count()

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

The syntax of the list.count() function is following.

list.count(elem)

Python List count(item) method returns the occurrence count of the given element in the list. If it’s greater than 0, it means 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']

Check if an element exists in the list using any()

Using Python any() function is the most classical way in which you can perform this task and also 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.

Check if the list contains an item using not in inverse operator.

Python “not in” is an inbuilt operator that evaluates to True if it does not finds a variable in the specified sequence and False otherwise.

To check if the list contains a particular item, you can use the not in inverse operator. Let’s see the following example.

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 all the items of another list 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.

See the following code.

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

Conclusion

There are many approaches you can use to determine whether an item exists in the list or not. For example, we have seen the following ways.

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

That is it for this tutorial.

How do you check if something is not in a list in Python?

Use the not in operator to check if an element is not in a list. Use the syntax element not in list to return True if element is not in list and False otherwise.

How do you check if items from one list are in another Python?

There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.

How do you find the uncommon element in two lists in Python?

The most efficient and recommended method to perform this task is using the combination of set() and map() to achieve it. Firstly converting inner lists to tuples using map, and outer lists to set, use of ^ operator can perform the set symmetric difference and hence perform this task.

How do you find common items in multiple lists in Python?

Find common elements from two lists in Python.
Using intersection() function. A simple and fairly efficient solution is to convert the first list into a set and then call the intersection() function. ... .
Using bitwise comparison. ... .
Using List Comprehension..