Python program to list the difference between two lists.



In Python, Lists are one of the built-in data type used for storing collections of data. Python list is a sequence of comma separated items, enclosed in square brackets[]. They are flexible, easy to manipulate and widely used in various applications.

In this article, we will explore to list the difference between two lists. Python provides the several built-in methods for achieving this.

Using set.difference() Method

The python set.difference() method is used to return the new set containing the elements that are present in the first set but not in any other sets provided as arguments.

Syntax

Following is the syntax of Python set.difference() method -

set.difference(*others)

In this approach, we will consider the two lists and convert them to sets using the set() and passing the argument to the set.difference() method to return the elements only in the first set.

Example

Let's look at the following example, where we are going to find the elements present in the 'list-x' but not in the 'list-y'.

x = [11,2,3,22]
y = [22,11]
result = list(set(x).difference(set(y)))
print("Result: ", result)

The output of the above program is as follows -

Result:  [2, 3]

Using List Comprehension

The second approach is by using the Python list comprehension, Where we loop through the first list to keep only the elements that does not exists in the another list.

Example

Consider the following example, where we are going to find the difference between two lists using the list comprehension.

x = ['ciaz', 'bmw', 'Audi']
y = ['cruze', 'ciaz']
result = [item for item in x if item not in y]
print("Result :", result)

The following is the output of the above program -

Result : ['bmw', 'Audi']

Using set.symmetric_difference() Method

In this approach we are going to use the python set.symmetric_difference() method, Which is used to return the elements present in either of two sets but not in both.

Syntax

Following is the syntax of Python set.symmetric_difference() method -

set.symmetric_difference(other)

Here, we will consider the two lists and convert them to sets using the set() and passing the argument to the set.symmetric_difference() method to return the elements unique to each list.

Example

Let's look at the following example, where we are going to find the elements present in the 'list-x' but not in the 'list-y'.

x = [11,2,32,3]
y = [32,11]
result = list(set(x).symmetric_difference(set(y)))
print("Result : ", result)

The output of the above program is as follows -

Result:  [2, 3]
Updated on: 2025-08-28T13:40:29+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements