W3docs

Get difference between two lists with Unique Entries

You can use the set data type to find the difference between two lists with unique entries.

You can use the set data type to find the difference between two lists with unique entries. The set data type only stores unique values, so it will automatically remove any duplicates. Here's an example code snippet in Python:

Get difference between two lists with Unique Entries in Python using sets

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

# Find the difference between the two lists
diff = list(set(list1) - set(list2))

print(diff)
# Output: [1, 2]

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

This will return a new list containing the unique elements that are in list1 but not in list2. You can also use the symmetric_difference() method of a set, which returns elements that are in either list but not in both.

Get difference between two lists with Unique Entries in Python using the symmetric_difference method

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

diff = list(set(list1).symmetric_difference(set(list2)))
print(diff)
# Output: [1, 2, 6, 7]

These two methods produce different results: the first calculates the set difference, while the second calculates the symmetric difference.