Skip to content

Difference between two lists elements | With & Without set() example

  • by

One of the best to find a Difference between two lists elements is the Python set() method. You will find many ways to do it, with and without the set() method.

Difference between two lists elements

Ways To Find The Difference Between Two Lists

  • Use Set()
  • Using Nested Loops
  • List Comprehension

Let’s See one by one Example

Use set()

This way will return those elements from list1 which don’t exist in the second. First, convert the lists into sets explicitly and then simply reduce one from the other using the subtract operator.

# Using set()

list1 = [1, 5, 0, 5, 3, 3, 4]
list2 = [2, 4, 3]
print(list(set(list1) - set(list2)))

Output: [0, 1, 5]

Using Nested Loops

Use nested For Loop and compare each element of the first list with the second list. Append every non-matching item to a new (and empty) list.

But in this way, you will get duplicates elements if present in the first list.

# Function 
def list_diff(list1, list2):
    out = []
    for ele in list1:
        if not ele in list2:
            out.append(ele)
    return out

# Test Input
list1 = [1, 5, 0, 5, 3, 3, 4]
list2 = [2, 4, 3]

# Run Test
print(list_diff(list1, list2))

Output: [1, 5, 0, 5]

List Comprehension

Another way using condition statements. Which called list comprehension syntax.

See the example below.

# Function
def list_diff(list1, list2):
    out = [item for item in list1 if not item in list2]
    return out

# Test Input
list1 = [1, 5, 0, 5, 3, 3, 4]
list2 = [2, 4, 3]

# Run Test
print(list_diff(list1, list2))

Output: [1, 5, 0, 5]

Do comment if you knew any other ways. If any doubts and suggestions on this article, please do comment below.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python program to get the difference of two lists are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading