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 Python 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']
Why are the resulting lists c and d not ordered?
The set() function does not retain the order. Every time you create a set from a list, or from anything, the items in the set can appear anywhere randomly.
Set operations
This is a list of all set operations, for reference.
| List Operation | Python | Blog Post |
|---|---|---|
| common items in lists | set(a) & set(b) |
find common items |
| difference between lists | set(a) - set(b) |
find difference |
| symmetric difference between lists | set(a) ^ set(b) |
find symmetric difference |
| union of lists | set(a) | set(b) |
find union |
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.