How to Compare Two Lists and Remove Duplicates in Python?

Estimated read time 2 min read

To compare two lists and remove duplicates in Python, you can convert the lists to sets and perform set operations. Here’s an example:

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

# Convert the lists to sets
set1 = set(list1)
set2 = set(list2)

# Find the common elements
common_elements = set1.intersection(set2)

# Remove the common elements from both lists
list1 = list(set1 - common_elements)
list2 = list(set2 - common_elements)

print(list1)
print(list2)

In this example, we have two lists, list1 and list2. To remove the duplicates, we convert both lists to sets using the set() function. Sets are unordered collections of unique elements.

Next, we find the common elements between the two sets using the intersection() method. This gives us a new set, common_elements, which contains the duplicates.

To remove the duplicates, we subtract the common_elements set from each set using the - operator. This gives us two new sets, set1 - common_elements and set2 - common_elements, which contain the elements unique to each set.

Finally, we convert these sets back to lists using the list() function and assign the results to list1 and list2. The resulting lists will contain only the unique elements from the original lists.

The output of the above code will be:

[1, 2, 3]
[6, 7, 8]

Note that the order of the elements in the resulting lists may not match the original order, as sets are unordered collections. If you need to preserve the order, you can use other approaches, such as using list comprehension or the filter() function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply