Skip to content

Python list difference | Example code

  • by

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 contains the items that are not on the second list.

Python lists different 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 the 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 the 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 or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *