Python list difference | Example code

Use in keyword or set.difference() or set.symmetric_difference() to find list difference in Python. The difference between the two lists means is one list containing the items that are not the second list.

Python list difference examples

Simple example code.

Use the in keyword

Get the difference between two lists by using a for-loop to iterate through the first list and Append element to a new list if it is not in the second list.

list1 = [1, 2, 4]
list2 = [4, 5, 0]
list_diff = []

for item in list1:

    if item not in list2:
        list_diff.append(item)

print(list_diff)

Output:

Python list difference

Use set.difference() method

First, convert both lists into sets and then use the set difference method to get the difference between both sets. Last converts the set difference into a list.

list1 = [1, 2, 4]
list2 = [4, 5, 0]

set_diff = set(list1) - set(list2)

list_diff = list(set_diff)

print(list_diff)

Output: [1, 2]

Use set.symmetric_difference() method

Same as above method convert both lists into sets then use set symmetric_difference() get the symmetric difference between both sets.

list1 = [1, 2, 4]
list2 = [4, 5, 0]

sd = set(list1).symmetric_difference(set(list2))

list_diff = list(sd)

print(list_diff)

Output: [0, 1, 2, 5]

Do comment if you have any doubts and suggestions on this Python list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe 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.