The Wayback Machine - https://web.archive.org/web/20250119101455/https://www.geeksforgeeks.org/python-difference-two-lists/
Open In App

Difference between two lists in Python

Last Updated : 13 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Calculating the difference between two lists in Python can be achieved in various ways, depending on the specific requirements. Using set operations is efficient for finding the difference when the order of elements and duplicates do not matter.

Python
a = [1, 2, 3, 4, 5]
b = [3, 4, 6, 7]

# Elements in list1 but not in list2
c = list(set(a) - set(b))

print(c) 

Output
[1, 2, 5]

Let’s explore other methods to find the difference between two lists in Python

Using collection.Counter

Using collections.Counter is a great approach when you want to handle duplicates explicitly while calculating the difference between two lists.

Python
from collections import Counter

# Define the lists
a = [1, 2, 3, 4, 5, 3]
b = [3, 4, 6, 7]

# Count occurrences in both lists
counter1 = Counter(a)
counter2 = Counter(b)

# Subtract the counts
c = counter1 - counter2

# Convert back to a list
result = list(c.elements())

print(result) 

Output
[1, 2, 3, 5]

Using List Comprehension

List comprehension is easy way to preserve the order and duplicates in the list. We can use this method to find the difference between two lists in a single line.

Python
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]

# Difference of 'a' and 'b' using list comprehension
c = [item for item in a if item not in b]

print(c)

Output
[1, 2]

Using filter() Function

filter() function can be used to filter elements that are in a but not in b. This approach preserves the order of elements and is efficient for small to medium-sized lists.

Python
a = [1, 2, 3, 4, 5]
b = [3, 4, 6, 7]

# Using filter to find elements in a but not in b
c = list(filter(lambda x: x not in b, a))

print(c)

Output
[1, 2, 5]

Next Article

Similar Reads

three90RightbarBannerImg