Skip to content

Python difference between two lists | Example code

  • by

You can use “in keyword” or list comprehension or set.difference() or set.symmetric_difference() to differentiate between two lists in Python.

Example difference between two lists in Python

A simple example code getting the difference between two lists results in a list containing the items in the first list but not the second.

Use the in keyword

Use a for-loop to iterate through the first list and check if the item is not in the second list.

list1 = ['One', 'Two', 'Three', 'Four']
list2 = ['One', 'Two']

list_difference = []

for item in list1:

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

print(list_difference)

Output:

Using list comprehension

It is a more compact implementation and recommended way compared to the upper example.

list1 = ['One', 'Two', 'Three', 'Four']
list2 = ['One', 'Two']

list_difference = [item for item in list1 if item not in list2]

print(list_difference)

Output: [‘Three’, ‘Four’]

Using set difference()

You have to convert both lists into sets and then use the set difference() where the set is the first set and s is the second set to get the difference between both sets.

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

set_difference = set(list1) - set(list2)
list_difference = list(set_difference)

print(list_difference)

Output: [1, 2]

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

Discover more from Tutorial

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

Continue reading