How to Find the Difference Between Two Lists in Python

Published January 29, 2025

How to Find the Difference Between Two Lists in Python How to Find the Difference Between Two Lists in Python

In Python, there is no method or function to find the difference between two lists. The difference between two lists a and b is the items in a but not present in b.

Create two lists a and b

For our example, we will createlists a and b having a few common items and a few different items.

a = ['apple', 'orange', 'mango', 'strawberry', 'papaya', 'banana']
b = ['durian', 'apple', 'orange', 'mango', 'papaya', 'banana']

Find the difference using set() and ^

Difference between a and b would mean a list with items present in a, but not present in b.

In this case, it a - b would be strawbeerry and b - a would be durian.

Unfortunately, there are not too many options in Python lists, but you can convert the lists to sets and perform the ^ operator between the sets.

We will create list c which contains the difference a - b and list d which contains b - a.

a - b

c = list(set(a) - set(b))
print(c)

Output:

['strawberry']

b - a

d = list(set(b) - set(a))
print(d)

Output:

['durian']

Full code

a = ['apple', 'orange', 'mango', 'strawberry', 'papaya', 'banana']
b = ['durian', 'apple', 'orange', 'mango', 'papaya', 'banana']

c = list(set(a) - set(b))
print(c)

d = list(set(b) - set(a))
print(d)

Output:

['strawberry']
['durian']

Conclusion

If you found this blog post useful, feel free to share it. Thanks for reading.

Related Posts

If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.

Disclaimer: Our website is supported by our users. We sometimes earn affiliate links when you click through the affiliate links on our website.

Last Updated: January 29, 2025.     This post was originally written on January 22, 2025.