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

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

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.

Output: [1, 5, 0, 5]

List Comprehension

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

See the example below.

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

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