Find elements in one list that are not in the other (Python)

avatar

Borislav Hadzhiev

Last updated: Aug 10, 2022

banner

Photo from Unsplash

Find elements in one list that are not in the other (Python) #

To find the elements in one list that are not in the other:

  1. Use the set() class to convert the first list to a set object.
  2. Use the difference() method to get the elements in the set that are not in the list.
  3. Use the list() class to convert the set object to a list.
main.py
list_1 = ['a', 'b', 'c'] list_2 = ['a', 'd', 'e'] result_1 = list(set(list_2).difference(list_1)) print(result_1) # 👉️ ['e', 'd'] # -------------------------------------- result_2 = list(set(list_1).difference(list_2)) print(result_2) # 👉️ ['b', 'c']

The first step is to use the set() class to convert the list to a set object.

Set objects have a difference() method that returns a new set with elements in the set that are not in the provided iterable.

In other words, set(list_2).difference(list_1) returns a new set that contains the items in list_2 that are not in list_1.

main.py
list_1 = ['a', 'b', 'c'] list_2 = ['a', 'd', 'e'] # 👇️ {'d', 'e'} print(set(list_2).difference(list_1))

The last step is to use the list() class to convert the result to a list.

main.py
list_1 = ['a', 'b', 'c'] list_2 = ['a', 'd', 'e'] result_1 = list(set(list_2).difference(list_1)) print(result_1) # 👉️ ['d', 'e']

Alternatively, you can use a list comprehension.

To find the elements in one list that are not in the other:

  1. Use a list comprehension to iterate over the list.
  2. Check if each element is not contained in the other list and return the result.
  3. The new list will only contain items from the first list that are not in the second list.
main.py
list_1 = ['a', 'b', 'c'] list_2 = ['a', 'd', 'e'] result_1 = [item for item in list_2 if item not in list_1] print(result_1) # 👉️ ['d', 'e'] # -------------------------------------- result_2 = [item for item in list_1 if item not in list_2] print(result_2) # 👉️ ['b', 'c']

We used a list comprehension to iterate over one of the lists.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we check if the item is not contained in the other list and return the result.

The new list contains all of the elements in the first list that are not in the second.

In other words, [item for item in list_2 if item not in list_1] returns all of the elements in list_2 that are not in list_1.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.