How to find the difference between two lists in Python
Created
Modified
Using Set Difference
A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
#!/usr/bin/python3
# -*- coding: utf8 -*-
l1 = ["a", "b", "c"]
l2 = ["b", "C"]
lst = list(set(l1) - set(l2))
print(lst)
# Sets
A = {"a", "b", "c"}
B = {"b", "C"}
# A - B
print(A-B)
# B - A
print(B-A)
['a', 'c'] {'a', 'c'} {'C'}
This will remove the duplicates in each list.
Using difference Method
Return a new set with elements in the set that are not in the others. For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
l1 = ["a", "b", "c"]
l2 = ["b", "C"]
lst = list(set(l1).difference(l2))
print(lst)
['a', 'c']
Returns the new slice of filtered values.
Using XOR Operator
Return the bitwise exclusive or of a and b. For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
a = ["a", "b", "c"]
b = ["b", "C"]
# xor operator
lst = list(set(a) ^ set(b))
print(lst)
['c', 'a', 'C']
This will show difference of a from b and b from a.
Using List Comprehension
If you want to preserve order of input list, try this:
#!/usr/bin/python3
# -*- coding: utf8 -*-
a = ["a", "b", "c"]
b = ["b", "C"]
# for loop
s = set(b)
lst = [x for x in a if x not in s]
print(lst)
['c', 'a', 'C']
This is an O(n) solution, faster than O(n*m) performance.
Using lambda Operator
It can be achieved using filter and lambda operator. For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
a = ["a", "b", "c"]
b = ["b", "a", "C"]
# for loop
lst = list(filter(lambda x:x not in a, b))
print(lst)
['C']